【发布时间】:2012-02-29 05:46:48
【问题描述】:
更新 - 转向一致的类型提供的解决方案
客户端将消息发送到服务器套接字,然后服务器以原始消息响应客户端。在引入后一种功能时,服务器只接收一条消息,而不是继续接收该消息,并且不响应客户端。评论了添加的行。任何有关挂断的见解都会很棒。
客户端、问题评论和响应代码更新:
{ private Socket socket = null;
private BufferedReader console = null;
private DataInputStream streamIn = null;
private DataOutputStream streamOut = null;
while (!line.equals(".bye"))
{ try
{ line = console.readLine();
streamOut.writeUTF(line); //Send console data to server socket
String reply = streamIn.readUTF(); //Recieve confirmation msg from server
System.out.println( reply ); //Print the msg
streamOut.flush();
}
public void start() throws IOException
{ console = new BufferedReader(new InputStreamReader(System.in)); //Changed console to BufferedReader
streamIn = new DataInputStream(socket.getInputStream());
streamOut = new DataOutputStream(socket.getOutputStream());
}
public void stop()
{ try
{ if (console != null) console.close();
if (streamOut != null) streamOut.close();
if (streamIn != null) streamIn.close(); //Is it good practice to close
if (socket != null) socket.close();
}
服务器端,问题已评论。
public void handleClient() throws IOException {
boolean done = false;
try {
System.out.println("Server Thread " + ID + " running.");
while (!done) {
String nextCommand = streamIn.readUTF();
if( nextCommand.equals(".bye") ) {
System.out.println("Client disconnected with bye.");
done = true;
} else {
System.out.println( nextCommand );
String nextReply = "\"You sent me ->" +nextCommand.toUpperCase() + "\"\n";
streamOut.writeUTF( nextReply );
}
}
} finally {
streamIn.close();
streamOut.close();
socket.close();
}
}
public void open() throws IOException
{
streamIn = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
streamOut = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));
// streamOut = new DataOutputStream(socket.getOutputStream());
}
public void close() throws IOException
{ if (socket != null) socket.close();
if (streamIn != null) streamIn.close();
if (streamOut != null) streamOut.close();
}
【问题讨论】:
-
这可以编译吗?不应该是 streamOut.writeBytes( nextReply.getBytes() ); ?