1

问题:

我编写了一个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();
        }



    }
}
4

1 回答 1

2

一旦你有一个传入连接,你应该将处理传入连接的责任委托给另一个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);
    }
}
于 2013-10-03T07:01:11.470 回答