码迷,mamicode.com
首页 > 其他好文 > 详细

ServerSocket

时间:2017-03-08 19:31:20      阅读:209      评论:0      收藏:0      [点我收藏+]

标签:oop   int   r.java   style   over   cat   log   color   tar   

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

标签:oop   int   r.java   style   over   cat   log   color   tar   

原文地址:http://www.cnblogs.com/duasonir/p/6521993.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!