m0_60945429
2022-02-11 18:45
采纳率: 87%
浏览 21
已结题

Java多线程服务器报错

我上网复制了一点服务器代码:

package ZTFZS;
import java.io.*;
import java.net.*;
 
/**
 * socket 服务端
 * @author xiaoming
 * @version 1.0
 * @date 2022-01-28
 */
public class A {
 
    public static String socketserver_ip = "127.0.0.1";
    public static int socketserver_port = 1024;
 
    public static void main(String[] args) throws IOException {
        startSocketForMoreThread();
    }
 
 
    /**
     * 多线程通信socket服务端
     */
    public static void startSocketForMoreThread() throws IOException {
        try{
        ServerSocket ss = new ServerSocket(socketserver_port);
        System.out.println("CommunicationServer启动服务器....端口为:"+socketserver_port+" wait connect...");
        while(true){
            Socket s = ss.accept();
            System.out.println("12");
            String r = new String("");
            System.out.println();
            //起一个线程处理
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        System.out.println("ok");
                        //读取和写入消息
                        readAndWriteMsg(s.getInputStream(),s.getOutputStream());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
 
                }
            }).start();
        }
    }catch (EOFException c){
         //TODO
    }
    }
 
    /**
     * 读取和写入消息
     * @param inp
     * @param outp
     * @throws IOException
     */
    public static void readAndWriteMsg(InputStream inp,OutputStream outp) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(inp));
        //持续读取客户端发送来的消息
        while(true) {
            System.out.println("CAN");
            Thread t = Thread.currentThread();
            String tname = t.getName();
            String mess = br.readLine();
            System.out.println("线程name="+tname+"【收到客户端信息】信息为:" + mess);
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(outp));
            bw.write("【服务端】已收到客户端发送消息,消息为:"+mess+"\n");
            bw.flush();
        }
 
    }
}
//But,它运行时突然报错:
//Exception in thread "main" java.net.BindException: Address already in use: bind
        //at java.base/sun.nio.ch.Net.bind0(Native Method)
        //at java.base/sun.nio.ch.Net.bind(Net.java:555)
        //at java.base/sun.nio.ch.Net.bind(Net.java:544)
        //at java.base/sun.nio.ch.NioSocketImpl.bind(NioSocketImpl.java:643)
        //at java.base/java.net.ServerSocket.bind(ServerSocket.java:388)
        //at java.base/java.net.ServerSocket.<init>(ServerSocket.java:274)
        //at java.base/java.net.ServerSocket.<init>(ServerSocket.java:167)
        //at ZTFZS.A.startSocketForMoreThread(A.java:26)
        //at ZTFZS.A.main(A.java:17)
         //不知道咋办
        //请高人指教
         //very感谢

1条回答 默认 最新

相关推荐 更多相似问题