我有一个Android客户端和一个使用相同套接字的java服务器互相发送一个字符串,但实际上不起作用,我不知道为什么。
无论如何,我只需要使用一个插座。
以下是客户端和服务器的代码:
public class CliActivity extends Activity implements OnClickListener {
Button b;
TextView tv;
BufferedReader in = null;
PrintStream out = null;
Socket client = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
b =(Button)findViewById(R.id.button1);
tv =(TextView)findViewById(R.id.textView1);
b.setOnClickListener(this);
}
public void onClick(View v) {
try {
client = new Socket("192.168.0.3",9000);
out = new PrintStream(client.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(client.getInputStream()));
out.write(("How are you?").getBytes());
out.close();
String message = in.readLine();
tv.setText(message);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
服务器:
public class server {
public static void main(String[] args) {
BufferedReader in = null;
PrintStream out = null;
Socket client = null;
try {
ServerSocket server = new ServerSocket(9000);
client = server.accept();
out = new PrintStream(client.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(client.getInputStream()));
String message = in.readLine();
System.out.println(message);
out.write(("fine thanx").getBytes());
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
有什么建议吗?