Java套接字编程

时间:2013-10-03 06:46:31

标签: java multithreading sockets serversocket

问题:

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



    }
}

1 个答案:

答案 0 :(得分:1)

一旦你有一个传入连接,你应该负责处理到另一个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);
    }
}