所以我有一个平板电脑,我想基本上把它做成一个 TCP(或 UDP)套接字服务器,这样多部手机就可以向它发送数据。我还希望能够将回复发送回手机。到目前为止我所拥有的不起作用...
服务器:
Log.i("Server", "Starting server...");
try {
ServerSocket ss = new ServerSocket(8080);
Log.i("Server", "Server status: " + ss.isBound());
while(true){
//Server is waiting for client here, if needed
Socket s = ss.accept();
Log.i("Server", "Server is accepting connections: " + s.isConnected());
BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
PrintWriter output = new PrintWriter(s.getOutputStream(),true); //Autoflush
Log.i("Server", "Initialized input and output");
String st = input.readLine();
Log.i("Server", "From client: "+st);
output.println("Good bye and thanks for all the fish :)");
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
和客户(电话):
try {
Socket s = new Socket("192.168.0.106", 8080);
//outgoing stream redirect to socket
OutputStream out = s.getOutputStream();
PrintWriter output = new PrintWriter(out);
output.println("Hello Android!");
BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
//read line(s)
String st = input.readLine();
tv.setText(st);
//Close connection
s.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}