首页 > 代码库 > ServerSocket

ServerSocket

All of codes are from GeekAcademy.

Use ServerSocket to create a chat server - 1

MyServerSocket.java

public class MyServerSocket {

    public static void main(String[] args) {

        new ServerListener().start();
    }
}

ServerListener.java

public class ServerListener extends Thread {

    @Override
    public void run() {
                
        try {
            ServerSocket serverSocket = new ServerSocket(12345);        
            while(true){
                Socket socket = serverSocket.accept();
                JOptionPane.showMessageDialog(null, "A client connects to the local port 12345");        
                new ChatSocket(socket).start();
            }            
        } catch (IOException e) {
            e.printStackTrace();
        }    
    }
}

ChatSocket.java

public class ChatSocket extends Thread {

    Socket socket;
    public ChatSocket( Socket s) {
        this.socket = s;
    }
    
    public void out(String out) {
        try {
            socket.getOutputStream().write(out.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    @Override
    public void run() {
        
        int count = 0;
        while(true){
            count++;
            out("loop: " + count + "  ");
            try {
                sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

 

ServerSocket