简单的客户端和服务端编程

2019-11-19  本文已影响0人  HannahLi_9f1c

TCP

1. 客户端代码

public class TCPEchoClient {
    public static void main(String args[]) throws IOException {
        byte[] data = "123456".getBytes();//获取字节数组
        Socket socket = new Socket("127.0.0.1",8080);//对于客户端来说,需要对服务端发起请求,绑定IP和端口
        InputStream in = socket.getInputStream();//输入流
        OutputStream out = socket.getOutputStream();//输出流
        out.write(data);//向服务端发送数据
        int totalBytesRecd = 0;
        int bytesRecd;
        while(totalBytesRecd < data.length) {
            if((bytesRecd = in.read(data, totalBytesRecd,
                    data.length-totalBytesRecd))==-1) {//读取服务端发送字节流
                throw new SocketException("Connection close prematurely");
            }
            totalBytesRecd+=bytesRecd;
        }
        System.out.println("Recd"+new String(data)+totalBytesRecd);
        socket.close();

    }
}

2. 服务端代码

public class TCPEchoServer {
    public static final int BUFSIZE = 32;
    public static void main(String[] args) throws IOException {
        ServerSocket server = new ServerSocket(8080);//服务端通过固定的端口提供服务,客户端的ip和地址都可以变化,但是服务端需要绑定Ip和服务。
        int recvMsgSize;
        byte[] recvbuf = new byte[BUFSIZE];
        while(true) {
            Socket cliSocket = server.accept();//监听客户端请求,建立起连接
            SocketAddress clientAddress = cliSocket.getRemoteSocketAddress();
            System.out.println("handling client at"+clientAddress);//输出客户端地址
            InputStream inputStream = cliSocket.getInputStream();
            OutputStream outputStream = cliSocket.getOutputStream();
            while((recvMsgSize = inputStream.read(recvbuf)) != -1) {
                outputStream.write(recvbuf, 0 , recvMsgSize);//将受到的字节,写出输出流
            }
            cliSocket.close();
        }

    }
}

3. 解析

UDP

1. 客户端

public class UDPEchoClient {
    public static final int TIMEOUT = 3000;//超时时间,防止UDP一直阻塞在等待读中,如果一直没有响应,就会发送失败
    public static final int MAXTRIES = 5;//由于数据报文可能丢失,我们必须准备好重新
//传输数据。本例中,我们最多循环5次,来发送数
// 据报文并尝试接收响应信息。
    public static void main(String [] args) throws IOException {
        InetAddress serverAddress = InetAddress.getLocalHost();
        byte[] byteToSend = "123456".getBytes();
        int servePort = 7;
        DatagramSocket socket = new DatagramSocket();
        socket.setSoTimeout(TIMEOUT);
        DatagramPacket sendPacket = new DatagramPacket(byteToSend,
                byteToSend.length, serverAddress, servePort );//发送的报文
        DatagramPacket receivePacket = new DatagramPacket(new byte[byteToSend.length],
                byteToSend.length);//接收报文
        int tries = 0;
        boolean receiveResponse = false;
        do{
            socket.send(sendPacket);
            try {
                socket.receive(receivePacket);
                if (!receivePacket.getAddress().equals(serverAddress)) {
                    throw new IOException("Received form an unknown source");
                }
                receiveResponse = true;
            }catch (InterruptedIOException e) {
                tries +=1;
                System.out.println("Time out");
            }
        } while ((!receiveResponse) && (tries < MAXTRIES));
        if(receiveResponse) {
            System.out.println("Received"+ new String(receivePacket.getData()));
        } else {
            System.out.println("No Response, give up");
        }
        socket.close();

    }
  1. 服务端
public class UDPEchoServer {
    private static final int ECHOMAX = 255;
    public static void main(String [] args) throws IOException {
        int servePort = 7;
        DatagramSocket socket = new DatagramSocket(servePort);
        DatagramPacket packet = new DatagramPacket(new byte[ECHOMAX], ECHOMAX);
        while(true) {
            socket.receive(packet);//接受报文
            System.out.println("Handling client at "+packet.getAddress().getHostAddress()
            +"on port" +packet.getPort());
            socket.send(packet);//复制并返回客户端
            packet.setLength(ECHOMAX);//最大长度255
        }
    }
}

3. 解析

上一篇 下一篇

猜你喜欢

热点阅读