java 网络编程(四)TCP通讯

客户端:

package cn.sasa.TcpDemo;

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

//客户端
public class TCPSocketDemo {

    public static void main(String[] args) throws IOException {
        Socket socket = new Socket("127.0.0.1",8040);
        //传ip和端口号,直接和服务器建立连接,如果连接失败,就抛异常
        OutputStream output = socket.getOutputStream();
        output.write("hello".getBytes());//往服务器写
        
        //读取服务器发回的数据
        InputStream input = socket.getInputStream();
        byte[] buff = new byte[1024];
        int len = input.read(buff);
        System.out.println(new String(buff,0,len));
        
        socket.close();
    }
}

服务器端:

package cn.sasa.TcpDemo;

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

//服务端
public class TCPServerSocketDemo {

    public static void main(String[] args) throws IOException {
        /**
         * java中的TCP和UDP的socket通信区别在于TCP通信区分服务器和客户端
         * TCP服务器:ServerSocket
         * TCP客户端:Socket
         * 
         * 客户端向服务器发送请求
         * 服务器接收客户端请求,建立连接,,两者之间通过IO流传输
         * 客户端向服务器发数据 output.write
         * 服务器接收 input.read
         * 服务器响应客户端 output.write
         * 客户端接收服务器消息 input.read
         * 
         * 服务器必须要获得客户端的套接字对象Socket,服务器需要知道是和谁的连接
         * Socket accept()
         */
        ServerSocket server = new ServerSocket(8040);
        Socket socket = server.accept();
        
        //获得输入流
        InputStream input = socket.getInputStream();
        byte[] buff = new byte[1024];
        int len = input.read(buff);
        System.out.println(new String(buff,0,len));
        
        //服务器向客户端发数据
        OutputStream output = socket.getOutputStream();
        output.write("received".getBytes());
        
        socket.close();
        server.close();
    }
}

 

posted @ 2019-01-22 15:48  SasaL  Views(176)  Comments(0Edit  收藏  举报