Java Tcp协议服务端和客户端传输数据

 

tcp协议,

优点:连接可靠,不会丢包,数据按先后顺序到达

缺点:速度慢,偶尔丢包

 

服务端:

public class tcpServer {
    public static void main(String[] args) throws IOException {
//        数据流传输
        ServerSocket serverSocket =null;
        OutputStream outputStream =null;
        DataOutputStream dataOutputStream=null;
        Socket socket =null;
        InputStream inputStream =null;
        DataInputStream dataInputStream =null;
//        ======================================================

        try {
            serverSocket = new ServerSocket(8080);//创建服务器端口
            System.out.println("---服务端已启动---");
//            让服务器循环,一直处理
            while (true){
                socket = serverSocket.accept();//接收并返回一个对象
//                取出消息
                inputStream = socket.getInputStream();//获取输入流
                dataInputStream = new DataInputStream(inputStream);//封装输入流内容
                String str = dataInputStream.readUTF();//拿到传输过来的文本信息
                System.out.println("接收到了客户端请求:" + str);


//                返回消息给客户端
                outputStream= socket.getOutputStream();
                dataOutputStream= new DataOutputStream(outputStream);
                String response= "hello";
                dataOutputStream.writeUTF(response);



            }


        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            serverSocket.close();
            socket.close();
            inputStream.close();
            dataInputStream.close();
        }

    }
}

 

客户端:

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

        Socket socket = new Socket();
        OutputStream outputStream = null;
        InputStream inputStream = null;
        DataInputStream dataInputStream = null;
        DataOutputStream dataOutputStream=null;

        socket= new Socket("127.0.0.1",8080);
        System.out.println("---客户端---");
        String request = "你好aaaa";
        System.out.println("客户端发送:" +request);
        outputStream= socket.getOutputStream();
        dataOutputStream = new DataOutputStream(outputStream);
        dataOutputStream.writeUTF(request);


//        接收服务器返回内容
        inputStream= socket.getInputStream();
        dataInputStream=new DataInputStream(inputStream);
        String response = dataInputStream.readUTF();
        System.out.println("服务器响应:" + response);


//        释放资源
        socket.close();
        outputStream.close();
        inputStream.close();
        dataInputStream.close();
        dataOutputStream.close();




    }
}

 

posted @ 2022-05-09 20:06  Hello霖  阅读(340)  评论(0编辑  收藏  举报