想象了下情況:如何:Java服務器套接字響應和客戶端閱讀
客戶端 -
客戶端發送到服務器 服務器的請求,服務器連接回答客戶 客戶端讀取答案
類客戶:
public class Client extends Service{
private String IP_ADDRESS;
private int PORT;
public void start(){
l.info("Starting client for server at: "+IP_ADDRESS+":"+PORT);
//Initialization of the client
try {
cs=new Socket(IP_ADDRESS,PORT);
} catch (UnknownHostException e) {
l.error("Unkown host at the specified address");
e.printStackTrace();
} catch (IOException e) {
l.error("I/O error starting the client socket");
e.printStackTrace();
}
}
//Sends the specified text by param
public void sendText(String text){
//Initializa the output client with the client socket data
try {
//DataOutputStream to send data to the server
toServer=new DataOutputStream(cs.getOutputStream());
l.info("Sending message to the server");
PrintWriter writer= new PrintWriter(toServer);
writer.println(text);
writer.flush();
} catch (IOException e) {
l.error("Bat initialization of the output client stream");
e.printStackTrace();
}
//Should show the answers from the server, i run this as a thread
public void showServerOutput(){
String message;
while(true){
//If there are new messages
try {
BufferedReader br= new BufferedReader(new InputStreamReader((cs.getInputStream())));
if((message=br.readLine())!=null){
//Show them
System.out.println(message);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
showServerOutput()
是返回任何方法答案由服務器發送
然後我的服務器類有下面的代碼
public class Server extends Service{
public void startListenner(){
l.info("Listening at port "+PORT);
while(true){
// Waits for a client connection
try {
cs=ss.accept();
l.info("Connection received: "+cs.getInetAddress()+":"+cs.getPort());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
toClient= new DataOutputStream(cs.getOutputStream());
PrintWriter cWriter= new PrintWriter(toClient);
//Send a confirmation message
cWriter.println("Message received");
//Catch the information sent by the client
csInput=new BufferedReader(new InputStreamReader(cs.getInputStream()));
printData();
toClient.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
正如你所看到的IM發送消息給客戶端的話:「收到的消息」,但它從來沒有在客戶端顯示安慰。怎麼了?
編輯
的printData()
方法打印在控制檯
public void printData(){
l.info("Printing message received");
try {
System.out.println(csInput.readLine());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
這個帖子在SO上問了很多次,你是否嘗試檢查相關的線程? – Omore
是的,我寫了這個之前做了一點研究,但沒有幫助我。我真的在想,創建一個已經被問了很多線程的事實,但正如我所說,我沒有在我的代碼中找到錯誤的東西。我對這個不必要的線程感到抱歉。 – JD0001