Android 客户端向服务器发送字符串。服务器将在正确的端口上确认来自设备的连接,仅此而已。应该发生的是在服务器控制台上打印字符串。
作为引用,我创建了完全相同的客户端,但没有在 Android 应用程序中运行它并且运行良好,所以这让我相信我在 Android 方面遗漏了一些东西。任何人都可以提出解决此问题的建议。非常感谢。
客户端代码:
public class ObjectTestActivity extends Activity {
Button submit;
TextView tv;
private String name = "Hello Android";
private DataOutputStream dos;
private DataInputStream dis;
private final int PORT = 3000;
Button send;
InetAddress host;
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
send = (Button) findViewById(R.id.send);
tv = (TextView) findViewById(R.id.tv);
try{
host = InetAddress.getLocalHost();
Socket socket = new Socket("xx.xx.xxx.xxx", PORT);
dos = new DataOutputStream(socket.getOutputStream());
dis = new DataInputStream(socket.getInputStream());
}catch(UnknownHostException e){}
catch(IOException e){}
}
public void onClick(View view){
try{
dos.writeUTF(name);
dos.flush();
dis.close();
dos.close();
}catch(IOException e){}
}
最佳答案
onClick 附加到什么?尝试更改为:
public class MyActivity extends Activity {
Button submit;
TextView tv;
private String name = "Hello Android";
private DataOutputStream dos;
private DataInputStream dis;
private final int PORT = 3000;
Button send;
InetAddress host;
protected void onCreate(Bundle icicle) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
send = (Button) findViewById(R.id.send);
tv = (TextView) findViewById(R.id.tv);
try{
host = InetAddress.getLocalHost();
Socket socket = new Socket("xx.xx.xxx.xxx", PORT);
dos = new DataOutputStream(socket.getOutputStream());
dis = new DataInputStream(socket.getInputStream());
}catch(UnknownHostException e){}
catch(IOException e){}
send.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try{
dos.writeUTF(name);
dos.flush();
dis.close();
dos.close();
}catch(IOException e){}
}
});
}
}
对于您的按钮 onClick 事件。
简单来说:在 onCreate (send.onCreate(...)) 中定义按钮的 onClick 方法。
这个例子来自here
关于android - 我的客户端将连接到服务器,仅此而已,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9548321/