Socket简单通信实例

服务端代码:

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


public class Server {

    /**
     * Socket服务端
     */
    public static void main(String[] args) throws IOException {

        ExecutorService executorService=Executors.newFixedThreadPool(1);
        ServerSocket serverSocket=new ServerSocket(8722);
        System.out.println("服务端启动!");

        while(true){
            Socket socket=serverSocket.accept();//监听并接受到此套接字的连接,返回一个Socket对象
            executorService.execute(new Handler(socket));
        }


    }

}

class Handler implements  Runnable{

    private Socket socket;

    public Handler(Socket socket) {
        this.socket=socket;
    }

    @Override
    public void run() {
        try {
            //根据输入输出流和客户端连接
            InputStream inputStream=socket.getInputStream();//得到一个输入流,接收客户端传递的信息
            InputStreamReader inputStreamReader=new InputStreamReader(inputStream);//提高效率,将自己字节流转为字符流
            BufferedReader bufferedReader=new BufferedReader(inputStreamReader);//加入缓冲区
            String temp=null;
            String info="";
            while((temp=bufferedReader.readLine())!=null){
                info+=temp;
                System.out.println("服务端接收到客户端信息:"+info+",当前客户端ip为:"+socket.getInetAddress().getHostAddress()+"端口为:"+socket.getPort());
            }

            OutputStream outputStream=socket.getOutputStream();//获取一个输出流,向服务端发送信息
            PrintWriter printWriter=new PrintWriter(outputStream);//将输出流包装成打印流
            printWriter.println("哈哈哈哈哈");
            printWriter.flush();
            socket.shutdownOutput();//关闭输出流

            //关闭相对应的资源
            printWriter.close();
            outputStream.close();
            bufferedReader.close();
            inputStream.close();
            socket.close();
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

客户端代码:

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


public class Client {

    /**
     * Socket客户端
     */
    public static void main(String[] args) throws IOException {

        ExecutorService executorService = Executors.newFixedThreadPool(1);

        while (true) {
            //创建Socket对象
            Socket socket = new Socket("192.168.1.2", 8722);
            executorService.execute(new Send(socket));
        }
    }

}

class Send implements Runnable {

    private Socket socket;

    public Send(Socket socket) {
        this.socket = socket;
    }


    @Override
    public void run() {
        try {
            //根据输入输出流和服务端连接
            OutputStream outputStream = socket.getOutputStream();//获取一个输出流,向服务端发送信息
            PrintWriter printWriter = new PrintWriter(outputStream);//将输出流包装成打印流
            printWriter.println("hello  服务端");
            printWriter.flush();
            socket.shutdownOutput();//关闭输出流

            InputStream inputStream = socket.getInputStream();//获取一个输入流,接收服务端的信息
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);//包装成字符流,提高效率
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);//缓冲区
            String info = "";
            String temp = null;//临时变量
            while ((temp = bufferedReader.readLine()) != null) {
                info += temp;
                System.out.println("客户端接收服务端发送信息:" + info + "服务端ip:" + socket.getInetAddress().getHostAddress() + " 端口为:" + socket.getPort());
            }

            //关闭相对应的资源
            bufferedReader.close();
            inputStream.close();
            printWriter.close();
            outputStream.close();
            socket.close();
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

这里用多线程设置了服务端和客户端每隔5秒进行通信。

服务端输出:可以看到每次连接的客户端的端口是在变化的。这是因为操作系统随机选的,一般客户端不需要bind固定端口。

客户端输出:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值