Java网络

Socket编程

2020-07-01  本文已影响0人  AbstractCulture

使用Socket模拟TCP与UDP通信

TCPServer

package com.xjm.socket;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class TcpServer {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(65000);
        while (true){
            //一直监听客户端的请求
            Socket accept = serverSocket.accept();
            //如果接收到请求,开启多线程处理任务
            new Thread(()->{
                try {
                    //获取socket的输出流
                    OutputStream outputStream = accept.getOutputStream();
                    //获取socket的输出流
                    InputStream inputStream = accept.getInputStream();
                    int ch = 0;
                    byte[] buff = new byte[1024];
                    //从socket的输入流中读取字节存在buff中,将长度赋值给ch
                    ch = inputStream.read(buff);
                    String content = new String(buff, 0, ch);
                    System.out.println(content);
                    String receive = "我是服务器,我收到了"+content.length()+"个字节";
                    //往输出流中写入信息,回发给客户端
                    outputStream.write(receive.getBytes());
                    //关闭连接
                    inputStream.close();
                    outputStream.close();
                    accept.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }
}

TCPClient

package com.xjm.socket;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

public class TcpCilent {
    public static void main(String[] args) {
        try {
            //连接到65000端口
            Socket socket = new Socket("127.0.0.1",65000);
            //获取socket的输出流
            OutputStream outputStream = socket.getOutputStream();
            //获取socket的输入流
            InputStream inputStream = socket.getInputStream();
            //往输入流中写入信息
            outputStream.write(new String("Hello Server").getBytes());
            int ch = 0;
            byte[] buff = new byte[1024];
            //从输出流中获取信息与长度
            ch = inputStream.read(buff);
            System.out.println(new String(buff,0,ch));
            //释放连接
            inputStream.close();
            outputStream.close();
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

输出结果:

TcpServer:Hello Server
TcpClient:我是服务器,我收到了12个字节

UDPServer

package com.xjm.socket;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.ServerSocket;
import java.net.Socket;

public class UDPServer {
    public static void main(String[] args) throws IOException {
        //服务端接收客户发送的数据报
        DatagramSocket datagramSocket = new DatagramSocket(65001);
        //存储从客户端接收的内容
        byte[] buf = new byte[100];
        DatagramPacket packet = new DatagramPacket(buf, buf.length);
        //接收客户端发送的内容,并将内容封装进DatagramPacket对象中
        datagramSocket.receive(packet);
        //从DatagramPacket对象中获取数据
        byte[] data = packet.getData();
        String content = new String(data, 0, packet.getLength());
        System.out.println(content);
        //转换成二进制
        byte[] sendData = String.valueOf(content.length()).getBytes();
        //从DatagramPacket对象中获取数据的来源地址与端口号
        DatagramPacket packetToClient = new DatagramPacket(sendData,
                sendData.length, packet.getAddress(), packet.getPort());
        //回发消息
        datagramSocket.send(packetToClient);
        //关闭资源
        datagramSocket.close();
    }
}

UDPClient

package com.xjm.socket;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class UDPClient {
    public static void main(String[] args) throws Exception{
        //发送数据报
        DatagramSocket datagramSocket = new DatagramSocket();
        //将发送的内容转成二进制
        byte[] bytes = "Hello Server".getBytes();
        //源地址
        InetAddress address =  InetAddress.getByName("127.0.0.1");
        //发送数据
        datagramSocket.send(new DatagramPacket(bytes,bytes.length, address,65001));

        //接收服务器回复的数据
        DatagramPacket datagramPacket = new DatagramPacket(new byte[100], 100);
        datagramSocket.receive(datagramPacket);
        //获取数据
        byte[] data = datagramPacket.getData();
        System.out.println(new String(data,0,data.length));
        datagramSocket.close();
    }
}

从实际的开发中,我们进一步感受到:TCP是面向字节流的,而UDP是面向报文的。TCP发送数据的时候,需要使用Socket通信,而UDP可以通过目的端口直接发送数据报。

上一篇下一篇

猜你喜欢

热点阅读