永发信息网

java中用Socket向ServerSocket发送信息,ServerSocket用接收到的Socket返回一条信息,但是返回时报错...

答案:4  悬赏:60  手机版
解决时间 2021-03-24 00:30
  • 提问者网友:我没有何以琛的痴心不悔
  • 2021-03-23 11:29
java中用Socket向ServerSocket发送信息,ServerSocket用接收到的Socket返回一条信息,但是返回时报错...
最佳答案
  • 五星知识达人网友:雾月
  • 2021-03-23 12:50
你 服务器端写完之后就关闭了,所以会包socket is closed.追问是服务器在接收到客户端Socket的时候开启一个线程专门和该客户端通信吗?
像这样:
Socket s = server.accept();
new Thread(new ClientThread(s)).start();
具体通信写在ClientThread里的run() 方法里的While(true)里么?追答不需要,你服务器端out.write(msg.getBytes()); out.close(); }
可以看出你服务器写完立马就关闭了。你把out.close()去掉试试追问不行,我现在吧服务器后面的写操作都删了,知道InputStream读出来那块,还是不行,现在客户端发消息都接收不到了,不知道发送到哪去了,方便的话能不能直接帮我改代码?追答已私信你
全部回答
  • 1楼网友:轻雾山林
  • 2021-03-23 15:46
while((t=in.read()) != -1) { <--改为 t=in.read(bytes) bytes[i] = (byte)t;
i++; }t的结果你独到的字节的个数 ,不是具体的值,具体的值已经保存到字节数组里面去了
应该这样
str += new String(bytes); 这样可以独到每一个具体的值
另外,你把out.close() 改成 out.flush() 你再测试下结果追问服务器和客户端的读操作都这么写么?改的那句应该放哪?如果方便请把循环整个具体写下,谢谢!追答字数超出最大允许值,请删减!
要的化,就发个邮箱追问问题已解决,谢谢您!
  • 2楼网友:北城痞子
  • 2021-03-23 15:21
 static int SERVERPORT=12345;
 
 public static void main(String[] args) throws Exception {  
    boolean flag = true;
    ServerSocket server = new ServerSocket(SERVERPORT);            
    while(flag) {                
     Socket s = server.accept();                
     DataInputStream in = new DataInputStream(s.getInputStream()); 
     String str = in.readUTF();                
     System.out.println(str);                
     DataOutputStream out = new DataOutputStream(s.getOutputStream());                
     String msg = "hello client";                
     out.writeUTF(msg);       
     out.flush();         
   s.close();
    } 
  } 
 
public static void main(String[] args) throws Exception {
  Socket s = new Socket("127.0.0.1", SERVERPORT);            
  DataOutputStream out = new DataOutputStream(s.getOutputStream());            
  String msg = "hello server";            
  out.writeUTF(msg);
  out.flush();          
  DataInputStream in = new DataInputStream(s.getInputStream());            
  String str = in.readUTF();            
  System.out.println(str);  
  s.close();
 }
注意:流不能关闭,调用流的close方法会导致socket关闭追问谢谢你!能不能改成基础流InputStream和OutputStream,因为我们要处理byte数组,我之前改的用基础流的没有关闭流也是用flush()但还是不行追答程序还是你自己写,就当是练手吧。
不要用read()==-1来判断是否结束,而改用先写要写出的byte[]的长度,接收时先读长度,然后再用read(byte[] b, int off, int len)读,直到读满长度为止
  • 3楼网友:零点过十分
  • 2021-03-23 14:02
while((t=in.read()) != -1) { bytes[i] = (byte)t; i++; } String str = new String(bytes); System.out.println(str);
改为
while((i=in.read(bytes))!=-1){
System.out.print(new String(bytes,0,1))
}追问客户端和服务器的读操作都这么写么?这句--System.out.print(new String(bytes,0,1))--什么意思?循环变量 i 和每次循环取得的 t 都没有意义了,麻烦详解下整个循环到底怎么写?
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯