开发者社区> 问答> 正文

JAVA多线程Socket通信时遇到的问题?

实验过程中,服务器和客户端都能连接上了,但是服务器就是收不到客户端发来的字符串。
screenshot
代码:

//Mult.java
package t14_chapter;
import java.io.*;
import java.net.*;
class Mult extends Thread{
private Socket socket;
private BufferedReader in;
private PrintWriter out;
public Mult(Socket s)throws IOException{
socket =s;
in=new BufferedReader(new InputStreamReader(s.getInputStream()));
out=new PrintWriter(new OutputStreamWriter(s.getOutputStream()),true);
start();
}
public void run() {
try{
while(true){
String str=in.readLine();
//wait(1000);
if(str.equals("END"))
break;
System.out.println("Receiving and echoing:"+str);
out.println(str);
}
System.out.println("closing...");
}catch(IOException e){}
finally{
try{
socket.close();
}catch(IOException e){}
}
}
}
//ServerSocketMult.java
package t14_chapter;
import java.io.*;
import java.net.*;
public class ServerSocketMult {
static final int PORT=8080;
public static void main(String[] args)throws IOException{
ServerSocket s=new ServerSocket(PORT);
System.out.println("Server Startes");
try{
while(true){
Socket socket=s.accept();
System.out.println("Connection success!");
try{
new Mult(socket);
}
catch(IOException e){}
finally{
socket.close();
}
}
}
catch(IOException e){}
finally{
s.close();
}
}
}
//ClientSocketMultThread.java
package t14_chapter;
import java.io.*;
import java.net.*;
class ClientSocketMultThread extends Thread{
private Socket socket;
private BufferedReader in;
private PrintWriter out;
private static int counter=0;
private int id=counter++;
private static int threadcount=0;
public static int threadCount(){
return threadcount;
}
public ClientSocketMultThread(InetAddress addr){
System.out.println("Making client"+id);
threadcount++;
try{
socket =new Socket(addr,ServerSocketMult.PORT);
}catch(IOException e){
    }
    try{
        in=new BufferedReader(new InputStreamReader(socket.getInputStream()));
        out=new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
        start();
    }catch(IOException e){
        try{
            socket.close();
        }catch(IOException e2){}
    }

}
public void run(){
    try{
        for(int i=0;i<25;i++){
            out.println("Client"+id+"i");
            String str=in.readLine();
            System.out.println(str);
        }
        out.println("END");
    }catch(IOException e){}
    finally{
        try{
            socket.close();
        }catch(IOException e){}
        threadcount--;
    }
    }
}
//ClientSocketMult.java
package t14_chapter;
import java.io.*;
import java.net.*;
public class ClientSocketMult {
static final int MAX_THREADS=40;
public static void main(String[] args)throws IOException,InterruptedException{
InetAddress addr=InetAddress.getByName(null);
while(true){
if(ClientSocketMultThread.threadCount()<MAX_THREADS)
new ClientSocketMultThread(addr);
Thread.sleep(100);
}
}
}

展开
收起
蛮大人123 2016-03-25 17:46:04 2446 0
1 条回答
写回答
取消 提交回答
  • 我说我不帅他们就打我,还说我虚伪

    测试了你的代码,存在的问题如下:
    1 你的ServerSocketMult类的finally{socket.close();}导致你的Mul线程刚开始处理Socket时,这个socket就已经关闭了。所以这个操作多余而且还是问题的根源,因为你已经咋Mul类处理完成后写了socket.close代码了。
    2 ClientSocketMult这个类启动指定N个线程,所以对线程数的操作threadcount--;是在多个线程中的,需要对threadcount变量进行同步操作。
    3 所有的异常分支,你都是空语句,所以淹没了异常导致你无法排错。其实收不到响应数据就是因为1中你关闭了Socket导致的,只要打印了异常就很容易定位的。
    修正ServerSocketMult代码:

     public class ServerSocketMult {
        static final int PORT = 8080;
    
        public static void main(String[] args) throws IOException {
            ServerSocket s = new ServerSocket(PORT);
            System.out.println("Server Startes");
            try {
                while (true) {
                    Socket socket = s.accept();
                    System.out.println("Connection success!");
                    new Mult(socket);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                s.close();
            }
        }
    }

    再修正Mult

     class Mult extends Thread {
        private Socket socket;
        private BufferedReader in;
        private PrintWriter out;
    
        public Mult(Socket s) throws IOException {
            socket = s;
            in = new BufferedReader(new InputStreamReader(s.getInputStream()));
            out = new PrintWriter(new OutputStreamWriter(s.getOutputStream()), true);
            start();
        }
    
        public void run() {
            System.out.println("print received ...");
            try {
                String str = in.readLine();
                StringBuffer buffer = new StringBuffer();
                //读取Socket的请求数据,并回应
                while (str!=null&&!str.equals("END")) {
                    buffer.append(str);
                    str = in.readLine();
                }
                String value = buffer.toString();
                out.println(value);
                System.out.println("Receiving and echoing:" + value);
                System.out.println("closing...");
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    修正ClientSocketMultThread

     class ClientSocketMultThread extends Thread {
        private Socket socket;
        private BufferedReader in;
        private PrintWriter out;
        private static int counter = 0;
        private int id = counter++;
        private static int threadcount = 0;
    
        public synchronized static int threadCount() {
            return threadcount;
        }
    
        public synchronized static void addThreadCount(){
            threadcount++;
        }
    
        public synchronized static void descThreadCount(){
            threadcount--;
        }
    
        public ClientSocketMultThread(InetAddress addr) {
            System.out.println("Making client" + id);
            threadcount++;
            try {
                socket = new Socket(addr, ServerSocketMult.PORT);
            } catch (IOException e) {
            }
            try {
                in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
                start();
            } catch (IOException e) {
                try {
                    socket.close();
                } catch (IOException e2) {
                }
            }
    
        }
    
        public void run() {
            try {
                for (int i = 0; i < 25; i++) {
                    out.println("Client" + id + i);
                }
                out.println("END");
    
                String str = in.readLine();
                System.out.println("getResponse:"+str);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    socket.close();
                } catch (IOException e) {
                }
    
                descThreadCount();
            }
        }
    }

    测试Ok,就能收到正确的请求及回复信息。

    2019-07-17 19:14:51
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
Spring Cloud Alibaba - 重新定义 Java Cloud-Native 立即下载
The Reactive Cloud Native Arch 立即下载
JAVA开发手册1.5.0 立即下载