这是我的问题,我有一个程序试图通过套接字连接进行通信。
- 我能够连接并发送" connect"给客户
-sendResponse(fromServer);收到" connect"并执行swtich并完成但是while循环(while(fromServer = in.readLine())!= null))不会中断而没有其他任何事情发生。
该计划就在那里。我究竟做错了什么?我大约一年前写过这篇文章而且我不知道我是怎么开始工作的。打印到他们系统的最后一件事是" Inside Connect"
这是我的代码:
服务器:
public static String socketTest(String action){
ServerSocket serverSocket;
Socket clientSocket;
PrintWriter out;
BufferedReader inBuff;
String fromClient = " ";
int port = 6000;
switch(action) {
case "sync":
out.println("sync");
while((fromClient = inBuff.readLine()) != null) {
log("Waiting for devices to sync");
Thread.sleep(1000);
}
break;
case "ready":
out.println("ready");
while((fromClient = inBuff.readLine()) != null) {
log("Waiting for Control PC response");
Thread.sleep(1000);
}
break;
case "connect":
String input = "",
output = "";
try {
log("**************************** Trying to listen to port 6000 ****************************");
serverSocket = new ServerSocket(port);
clientSocket = serverSocket.accept();
out = new PrintWriter(clientSocket.getOutputStream(), true);
inBuff = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
//out.println("I am the test machine and we have connected to port 6000");
out.println("connect");
log("**************************** Should be listening to port 6000 now ****************************");
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//while((fromClient = inBuff.readLine()) != null) {
// log("Waiting for Control PC response");
// Thread.sleep(1000);
//}
break;
} // Close switch statement
return fromClient;
}
客户端:
while ((fromServer = in.readLine()) != null) {
System.out.println("in while ((fromServer = in.readLine()) != null)");
System.out.println("This should be the first thing from server: " + fromServer + "\n");
sendResponse(fromServer);
}
sendResponse fucntion:
public static String sendResponse(String action) throws InterruptedException, IOException {
String str = " "; // Value to hold string to be returned
switch (action) {
case "connect":
System.out.println("Inside connect");
out.println("success");
break;
case "ready":
System.out.println("Inside ready");
out.println("success");
break;
case "sync":
System.out.println("Inside sync");
Thread.sleep(10000);
out.println("success");
break;
default:
out.println(" ");
}
return str;
}