java的socket学习

来源:互联网 发布:php网站源码搭建 编辑:程序博客网 时间:2024/05/16 19:10

多次交互的Client端

public class Client {

    public static void main(String[] args) throws Exception{
        Socket client = new Socket("127.0.0.1",8888);
        PrintStream out = new PrintStream(client.getOutputStream(),true);
        BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
        Console console = System.console();
        String line1 = console.readLine();
        while(line1!=null){
            out.println(line1);
            line1 = console.readLine();
        }
        String line2 = in.readLine();
        System.out.println(line2);
        out.close();
        in.close();
    }

}


加入多线程功能

public class Process implements Runnable {
    
    private Socket socket;
    
    public Process(Socket socket){
        this.socket = socket;
    }
    @Override
    public void run() {
        try {
            PrintStream out = new PrintStream(socket.getOutputStream(),true);
            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));            
            out.println("gun");
            String line = in.readLine();
            while(line!=null){
                line = in.readLine();
                System.out.println(line);
            }
            out.close();
            in.close();
        } catch (IOException e) {

            e.printStackTrace();
        }

    }

}


Server端

public class Server {
    
    public static void main(String[] args) throws Exception {
        ServerSocket server = new ServerSocket(8888);
        while(true){
            Socket socket = server.accept();
            Process pro = new Process(socket);
            Thread th = new Thread(pro);
            th.start();
            }
    }
    
}


原创粉丝点击