TCP实现通信

77 阅读1分钟

服务端

package com.socket;

import com.oop.demo04.B;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class SocketServer {
    public static void main(String[] args) {
        ServerSocket serverSocket = null;
        Socket socket = null;
        InputStream in = null;
        ByteArrayOutputStream bos = null;
        try {
            serverSocket = new ServerSocket(9999);
            socket = serverSocket.accept();
            in = socket.getInputStream();
            byte[] buffer = new byte[1024];
            bos = new ByteArrayOutputStream();
            while (in.read(buffer) != -1){
                bos.write(buffer);
            }
            System.out.println(bos.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if (bos != null){
                    bos.close();
                }
                if (in != null){
                    in.close();
                }
                if (socket != null){
                    socket.close();
                }
                if (serverSocket != null){
                    serverSocket.close();
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }


    }
}

客户端

package com.socket;

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

public class SocketClient {
    public static void main(String[] args) {
        Socket socket = null;
        OutputStream outputStream = null;
        try {
            socket = new Socket("localhost",9999);
            outputStream = socket.getOutputStream();
            outputStream.write("你好好哈好好奥佛奥发".getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if (outputStream != null){
                    outputStream.close();
                }
                if (socket != null){
                    socket.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}