我无法使用 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 上暂停,请帮助