[英]DataInputStream from socket
更新-移至提供一致類型的解決方案
客戶端將消息發送到服務器套接字,然后服務器用原始消息響應客戶端。 當引入后一種功能時,服務器僅接收一個消息,而不繼續接收所述消息,並且不響應客戶端。 評論了添加的行。 對掛斷的任何見解都是很棒的。
客戶端,已評論的問題和響應中的代碼更新:
{ 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();
}
您正在使用writeUTF和readUTF,但是在一個地方streamIn.readLine()中,我希望它在等待新行時會阻塞。 我懷疑您需要始終使用readUTF。
順便說一句,控制台不是數據流,而是文本,我建議您使用BufferedReader。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.