为什么老是点发送键无接收,其中客户端就一个发送按钮,服务端界面为一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();
}
}
}