两部android手机 连接同一wifi socket通信 实现时出错(一台当服务器,一台当客户端)

为什么老是点发送键无接收,其中客户端就一个发送按钮,服务端界面为一textView。
服务器代码:
public class ServerActivity extends Activity {
public final static int port = 7777;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tv = (TextView) findViewById(R.id.content_from_client);

BufferedReader in;
try {
System.out.println("try to connect...");
ServerSocket serverSocket = new ServerSocket(port);
while (true) {
Socket client = serverSocket.accept();
in = new BufferedReader(new InputStreamReader(
client.getInputStream()));
String str = in.readLine();
tv.setText(str);
in.close();
client.close();
}
} catch (Exception e) {
e.printStackTrace();
}

}

}
客户端代码:
public class ClientActivity extends Activity {
public final static String ip = "192.168.81.105";
public final static int port = 7777;
private Button btnSend;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnSend = (Button) findViewById(R.id.send_btn);
btnSend.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View arg0) {
sendMsg(ip, port, "hello from client");

}
});

}

private void sendMsg(String ip, int port, String msg) {
Socket socket;
try {

socket = new Socket(ip, port);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
socket.getOutputStream()));
writer.write(msg);
Log.w("msg", "has send");
writer.flush();
writer.close();
socket.close();

} catch (Exception e) {
e.printStackTrace();
}

}
}

你用logcat语句检查下代码执行到哪,看下有没有异常。
还有做socket通信,不要把通信代码放在主界面的Thread,这样很容易引起异常,最好写一个子线程。
温馨提示:答案为网友推荐,仅供参考
相似回答