ServerSocket

Posted Winter boy

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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的主要内容,如果未能解决你的问题,请参考以下文章

delphi serversocket与clientsocket通讯的问题?

网络编程socketserver的方法都有哪些

Java 实例演示-ServerSocket 和 Socket 通信实例

Java网络编程精解之ServerSocket用法详解二

刚安装了IntelliJIDEA 10 ,可是安装好了之后 String、Long、ServerSocket类无法识别。。。代码报错 !@@@

Java网络编程-第四节:TCP流套接字(ServerSocket)编程