我无法使用java从客户端获取服务器中的数据 以下是我的服务器代码:
public void UpdateClients() throws Exception{
Socket socktmp=null;
try
{
socktmp= mainSocket.accept();
rdr= new BufferedReader( new InputStreamReader(socktmp.getInputStream()));
String t="";
String name="";
while((t=rdr.readLine())!=null){ <<<<< **it stops here**
name=t;
}
//rdr.close();
LstClient.AddClient(name, socktmp);
objwriter = new ObjectOutputStream(socktmp.getOutputStream());
objwriter.writeObject(LstClient.clients);
objwriter.flush();
objwriter.close();
}
catch(Exception ex){
throw new Exception("Unable to Update Clients. Error :" + ex.getMessage());
}
finally{
try{
if(mainSocket!=null){
mainSocket.close();
}
if(socktmp!=null){
socktmp.close();
}
if(rdr!=null)
{
rdr.close();
}
if(objwriter!=null)
{
objwriter.close();
}
}
catch(Exception ex1){
throw new Exception("Unable to close streams after opeining. Error :"+ ex1.getMessage());
}
}
}
以下是我的客户端代码:
public Client(String serverIp,int port,String name) throws Exception{
try{
if(mainSock!=null){
mainSock.close();
}
mainSock= new Socket(serverIp, port);
writer= new BufferedWriter(new OutputStreamWriter(mainSock.getOutputStream()));
writer.write(name);
writer.flush();
**//writer.close();**
Thread.sleep(1500);
objin = new ObjectInputStream(mainSock.getInputStream());
Hashtable<String,Socket> lst= new Hashtable<String , Socket>();
lst = (Hashtable<String, Socket>) objin.readObject();
cl = new LstClient();
LstClient.clients = lst;
System.out.println(LstClient.clients.size());
objin.close();
}
catch(Exception ex){
throw new Exception("Error : "+ ex.getMessage());
}
finally{
if(mainSock!=null){
mainSock.close();
}
if(writer!=null){
writer.close();
}
if(objin!=null){
objin.close();
}
}
}
当我关闭客户端的编写器时,我仅在服务器中获取数据或光标继续在服务器端读取行。但是当我在客户端关闭编写器后尝试读取时,它说套接字已关闭,因此如果不关闭它会在服务器端的 readline 上暂停 请帮忙
最佳答案
我在使用 readLine 时最常犯的错误是忘记发送新行。
您正在发送没有换行的文本,即 \n
但仍然等待它发送。
尝试添加write('\n');
关于java - 服务器套接字不断读取数据,直到我从 Java 客户端关闭套接字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14202654/