问题:

我编写了一个Java套接字服务器,当我从客户端向它发送第一条消息时它会发送响应。但是我想根据第一个响应再发送一条消息。在第一个响应之后,我没有收到其他任何响应?

这是服务器代码:

public class SendSmsServerSocket {

    private final static CxpsLogger logger = CxpsLogger.getLogger(SendSmsServerSocket.class);

    SendSmsServerSocket(){
        try {
            new SeverSocketForSms(new ServerSocket(4330));
        } catch (IOException e) {
        e.printStackTrace();
        }

    }
}


private static class SeverSocketForSms extends Thread {

    private  Socket socket;
    private  ServerSocket serversocket;
    private volatile static boolean running = true;

    public SeverSocketForSms(ServerSocket ssocket) throws IOException {
        this.serversocket = ssocket;
        start();
    }

    public void run() {
        try{
        while(running) {
            this.socket = serversocket.accept();
            InputStreamReader ir = new InputStreamReader(socket.getInputStream());
            BufferedReader br = new BufferedReader(ir);
            String msg = br.readLine();

            PrintStream ps = new  PrintStream(socket.getOutputStream());
            ps.println("inside SeverSocketForSms: msg received is :  "+msg);
        }


        }
        catch(Exception e){
        e.printStackTrace();
        }
        catch(Throwable t) {
        System.out.println("Caught " + t + "xmlServerThread - closing thread");
        }
    }

    public static void shutdown() {
        System.out.println("Stopping socket connection and thread");
        try{
            socket.close();
        }catch (Exception e) {
            e.printStackTrace();
        }
        running = false;
    }



    public static void main (String [] args){
        try {
            System.out.println("Starting sms server ----- Please press Enter Key to stop the server after receiving one message");
            SendSmsServerSocket s=new SendSmsServerSocket();

            new Scanner(System.in).nextLine();
            SeverSocketForSms.shutdown();


        } catch (Exception e) {
            e.printStackTrace();
        }



    }
}

最佳答案

建立传入连接后,应委派处理该传入连接到另一个Thread的责任,否则将阻塞“接受”线程,直到关闭当前连接为止。

while (running) {
    this.socket = serversocket.accept();
    Thread thread = new Thread(new Handler(socket));
    thread.start();
}


还有Handler

public class Handler implements Runnable {
    private Socket socket;
    public Handler(Socket socket){
        this.socket = socket;
    }

    public void run() {
        // You may need to add a repeat and exit clause here...
        InputStreamReader ir = new InputStreamReader(socket.getInputStream());
        BufferedReader br = new BufferedReader(ir);
        String msg = br.readLine();

        PrintStream ps = new PrintStream(socket.getOutputStream());
        ps.println("inside SeverSocketForSms: msg received is :  " + msg);
    }
}

08-24 18:42