Java Socket 异常 Socket 关闭

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21578953/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 09:29:07  来源:igfitidea点击:

Java Socket Exception Socket Closed

javasockets

提问by user3275415

I am trying to write a chat application using java sockets... The Concept is Server listens on a port for clients when client comes in as the first step the server will store as username and client's link socket as sockettuple(An object which has username as string and linksocket as socket) .. then after storing it sends the client as welcome you are connected ..Server listens in listenthreadand communications happen in separate thread.. for client creation of socket happens in main thread and writing to server happens in separate thread In this the storing of socket tuple happens fine but on sending the message from server to client Socketclosed exceptionhappens on both server write and client's read threads......

我正在尝试使用 java 套接字编写一个聊天应用程序......概念是当客户端进入时服务器会监听客户端的端口作为第一步服务器将存储为用户名和客户端的链接套接字为sockettuple(一个对象,其用户名为字符串和链接套接字作为套接字)..然后在存储它之后发送客户端作为欢迎你连接..服务器侦听listenthread和通信发生在单独的线程..客户端创建套接字发生在主线程中,写入服务器发生在单独的线程中在这种情况下,套接字元组的存储发生得很好,但是从服务器向客户端发送消息Socketclosed exception时,服务器写入和客户端的读取线程都会发生......

// mainserver.java

import java.net.*;
import java.io.*;


class listenthread extends Thread{
?ServerSocket mserver;
?Socket link,targetsocket;
?String user,targetuser;
?sockettuple targettuple,starray[]= new sockettuple[10];
?
?
?int i=0;
?
?public listenthread(ServerSocket mserver){
?try{
?System.out.println("Inside Listenthread constructor");
? this.mserver=mserver;
?
?
?}
?catch (Exception e){
?System.out.println("Exception inside listenthread constructor"+e);
?}
?
?}
?public void  run(){
?try{
?
? while(true){
?
? System.out.println("Listening.....");
? link=mserver.accept();
?
? System.out.println("Accepted");
? BufferedReader intosockb = new BufferedReader(new InputStreamReader(link.getInputStream()));
? user= intosockb.readLine();
?
?
? System.out.println(user + "Accepted");
?
? starray[i] =new sockettuple(link,user);
? i++;
? System.out.println(starray[i-1].username);
?
? ?new servwrite(link).start();
? ?
? ?intosockb.close();
? ?
? }
?
?}
?catch(Exception e){
?System.out.println("Exception inside listenthread run "+e);
?e.printStackTrace();
?}
?}
?}


class servwrite extends Thread{ 
?Socket link;
?
?public servwrite(Socket link){
?this.link=link;
?}
?public void run(){
?try{
?PrintStream fromserv=new PrintStream(link.getOutputStream());
? fromserv.print("You are  connected...Enter the target user:");
? ?
?}
?catch(Exception e){
?System.out.println("Exception inside run of serv write thread..."+e);
?}
?}
}
?
public class mainserver {
?
?public static void main(String args[]){
?try{
?
?ServerSocket Servermain= new ServerSocket(4579);
?
?System.out.println(" Server main Socket created");
?
?new listenthread(Servermain).start();
?
?
?
?
?}
?catch(Exception e){
?System.out.println("Exception inside main "+e);
?}
?
}
}



//Clientmenu.java

import java.net.*;
import java.io.*;

class clientread extends Thread{
?Socket client;
?BufferedReader key=null;
?public clientread(Socket client){
?try{
?this.client=client;
? key= new BufferedReader(new InputStreamReader(client.getInputStream()));
?}
?catch(Exception e){
?System.out.println("Exception inside client read thread's constructor");
?e.printStackTrace();
?}
?
?}
?public void run(){
?try{
?System.out.println("First line inside run of client read thread before cmsg readline");
?String cmsg= key.readLine();
?System.out.println(cmsg);
?}
?catch(Exception e){
?System.out.println("Exception inside run of client read thread..."+e);
?e.printStackTrace();
?}
?}
}

public  class Clientmenu {
?
   public static void main(String args[]){
   ?String user=" ";
   ?String targetuser="";
   ?Socket newclient;
   ?BufferedReader fromtheserv;

   ?try{
   ?
   ?newclient = new Socket("127.0.0.1",4579);
   ?System.out.print("Enter username:");
   ?BufferedReader key= new BufferedReader(new InputStreamReader(System.in));
       ?user=key.readLine();
       ?
       ?PrintStream fromclientp=new PrintStream(newclient.getOutputStream());
     ? fromclientp.print(user);
     ?

     ?new clientread(newclient).start();
   ?
   ?
       ?
  ?
  ?

   ?fromclientp.close();
   ?
   ?
   ?  
   ?
   ?
           }
   ?
   ?catch(Exception e){
   ?System.out.println("Exception inside CLientmenu "+e);
   ?}
}
}

回答by user207421

'Socket closed' means that youclosed the socket and then continued to use it. It's a bug in your code.

'Socket closed' 意味着关闭了socket,然后继续使用它。这是您代码中的错误。

Note that it does notmean that the peer closed the connection.

请注意,它意味着对关闭了连接。

There are numerous problems with your code, too many to review here. It is very poor quality. I suggest you get hold of the Custom Networking trail of the Java Tutorial and study it, and also look around for best practices in exception handling. At present you just catch certain exceptions, log them, and continue as though they hadn't happened. Code after a 'catch' block should not rely on things that happened in the 'try' block.

你的代码有很多问题,太多了,无法在这里查看。它的质量很差。我建议您掌握 Java 教程的自定义网络跟踪并研究它,同时也寻找异常处理的最佳实践。目前你只是捕捉某些异常,记录它们,然后继续,就好像它们没有发生一样。“catch”块之后的代码不应依赖于“try”块中发生的事情。

回答by Hamza Zafar

Closing the "Buffered reader" in listenThread and "PrintStream" in clientMenu causes the issue. When you close the returned Input / Output Stream, the underlying socket also gets closed.

关闭 listenThread 中的“Buffered reader”和 clientMenu 中的“PrintStream”会导致该问题。当您关闭返回的输入/输出流时,底层套接字也会关闭。

Refer to the documentation here

请参阅此处的文档

I hope this solves the problem.

我希望这能解决问题。

回答by cool cool

try to remove this line in run method of listenthread class.

尝试在 listenthread 类的 run 方法中删除这一行。

intosockb.close();

that is closing the stream, which is closing the socket.

即关闭流,即关闭套接字。