java socket多线程通讯demo

package com.yws.echo_socket;

import java.io.*;
import java.net.Inet4Address;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class EchoServer {


    private static ExecutorService executorService = Executors.newFixedThreadPool(5);

    public EchoServer(int port) throws IOException {

        ServerSocket serverSocket = new ServerSocket(port);
        String address = Inet4Address.getLocalHost().getHostAddress();
        System.out.println("starting echo server on " + address + ":" + port);
        while (true) {
            Socket socket = serverSocket.accept();
            executorService.execute(new Runnable() {
                @Override
                public void run() {

                    try {
                        doaccept(socket);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });


        }
    }

    private void doaccept(Socket socket) throws IOException {

        System.err.println(Thread.currentThread().getName() + " accept connection from client");

        InputStream in = socket.getInputStream();
        OutputStream out = socket.getOutputStream();

        String line;
        int len;

        byte[] buffer = new byte[1024];
        while ((len = in.read(buffer)) != -1) {
            byte[] data = new byte[len];
            System.arraycopy(buffer, 0, data, 0, len);
            System.out.print(new String(data, 0, len));
            out.write(buffer, 0, len);
            out.flush();
        }
        /*
        BufferedReader is = new BufferedReader(new InputStreamReader(in));
        BufferedWriter os = new BufferedWriter(new OutputStreamWriter(out));

        while ((line = is.readLine()) != null) {

            os.write("来自server" + line);
            os.flush();
            System.out.println("来自server" + line);
        }
        os.close();
        is.close();
        */


        System.err.println(Thread.currentThread().getName() + " closing connection with client");
        in.close();
        out.close();
        socket.close();

    }

    public static void main(String[] args) throws IOException {

        int port = 4444;
        if (args.length == 2) {
            port = Integer.parseInt(args[1]);
        }
        new EchoServer(port);
    }
}

package com.yws.echo_socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class EchoClient {

    private static  boolean isacceptData=true;
    private static   ExecutorService executorService= Executors.newFixedThreadPool(2);

    public EchoClient(String ip,int port)
    {
        try {
            Socket socket = new Socket(ip, port);
            System.out.println(ip+":"+port);
            sendData(socket);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //ssh -L 192.168.0.102:9999:192.168.1.140:4444 localhost
    public static void main(String args[]) {

        int  port=9999;
        String ip="192.168.0.102";
        if(args.length==3)
        {
            ip=args[1];
            port=Integer.parseInt(args[2]);
        }
        new EchoClient(ip,port);
    }
    public  void sendData(Socket socket) throws InterruptedException, IOException {

        executorService.execute(new Runnable() {
            @Override
            public void run() {

                try {
                    for(int i=1;i<=15;i++)
                    {
                        writedata(socket, "data"+i);
                    }
                    isacceptData=false;

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });

        executorService.execute(new Runnable() {
            @Override
            public void run() {

                try {
                    readdata(socket);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
      // executorService.awaitTermination(2, TimeUnit.SECONDS);
       // System.out.println(Thread.activeCount());
       // socket.close();
        //executorService.shutdown();


    }

    private void writedata(Socket socket, String data) throws IOException {

        PrintWriter os = new PrintWriter(socket.getOutputStream());
        os.println(data);
        os.flush();
        System.out.println(Thread.currentThread().getName()+" write:" + data);
        data="数据";
        os.println(data);
        os.flush();
        System.out.println(Thread.currentThread().getName()+" write:" + data);
    }

    private void readdata(Socket socket) throws IOException {

        BufferedReader is = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        String line;
        while((line=is.readLine())!=null && isacceptData)
        {
            System.out.println(Thread.currentThread().getName()+" read from Server:" + line);

        }

        socket.close();
        executorService.shutdown();


    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值