我已经使用 Socket 框架在我的手机和计算机之间建立了连接。只要我只需要发送一个命令,它就可以正常工作。然后我必须重新启动服务器才能接收新命令。你能帮我弄清楚为什么吗?我希望能够发送多个命令。
我正在从 GUI 主类调用类方法。
我的服务器代码:
public class Server {
private static PrintWriter out;
private static BufferedReader in;
private static ServerSocket serverSocket = null;
private static Socket clientSocket = null;
private static String inputLine, outputLine;
public static void main() throws IOException {
try {
serverSocket = new ServerSocket(4444);
System.out.println(serverSocket.getInetAddress().toString());
} catch (IOException e) {
System.err.println("Could not listen on port: 4444.");
System.exit(1);
}
try {
clientSocket = serverSocket.accept();
} catch (IOException e) {
System.err.println("Accept failed.");
System.exit(1);
}
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(
new InputStreamReader(
clientSocket.getInputStream()));
Protocol kkp = new Protocol();
outputLine = kkp.processInput(null);
out.println(outputLine);
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
outputLine = kkp.processInput(inputLine);
out.println(outputLine);
}
}
public static void shutDown() throws IOException
{
System.exit(1);
out.close();
in.close();
clientSocket.close();
serverSocket.close();
}
}
我的客户代码:
class ClientThread implements Runnable {
public void run() {
Socket kkSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
kkSocket = new Socket(serverAddr, 4444);
out = new PrintWriter(kkSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(kkSocket.getInputStream()));
} catch (UnknownHostException e) {
showToast("Kan ikke finde host fra: "+settings.getString("ip", "86.52.16.102"));
System.err.println("Don't know about host: taranis.");
System.exit(1);
} catch (IOException e) {
showToast("Kan ikke udveksle oplysninger med: "+settings.getString("ip", "86.52.16.102"));
System.err.println("Couldn't get I/O for the connection to: taranis.");
System.exit(1);
}
String fromServer;
String fromUser;
try {
while ((fromServer = in.readLine()) != null) {
System.out.println("Server: " + fromServer);
if (fromServer.equals("Shutting down") || fromServer.equals("Wrong pin!"))
{
showToast(fromServer);
break;
}
//fromUser = stdIn.readLine();
fromUser = pinkode.getText().toString()+","+time;
if (fromUser != null) {
System.out.println("Client: " + fromUser);
out.println(fromUser);
fromUser = null;
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
out.close();
try {
in.close();
kkSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}