[javaSE] 网络编程(TCP服务端客户端互访阻塞)

客户端给服务端发送数据,服务端收到数据后,给客户端反馈数据

客户端:

获取Socket对象,new出来,构造参数:Stringip地址,int的端口号

调用Socket对象的getOutputStream()方法,获取到OutputStream对象

调用OutputStream对象的write()方法,输出流输出数据,参数:byte[]字节数组

调用Socket对象的getInputStream()方法,获取到InputStream对象

调用InputStream对象的read()方法,读取数据得到读取的长度,参数:byte[]字节数组

获取String对象,new出来,构造参数:byte[]字节数组,0开始,len长度

调用Socket对象的close()方法,关闭socket

客户端的输入流读取read()方法,是阻塞式方法,会在这里等待服务端返回数据

服务端:

获取ServerSocket对象,new出来,构造参数:int的端口号

调用ServerSocket对象的accept()方法,得到Socket对象

调用Socket对象的getInputStream()方法,得到输入流对象,解析输入流

调用Socket对象的getOutputStream()方法,得到输出流对象,输出数据

调用Socket对象的close()方法,关闭socket

调用ServerSocket对象的close()方法,关闭ServerSocket

服务端的accept()方法,是阻塞式方法,会在这里等待客户端的连接

 Server.java

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

/**
 * 服务端
 * 
 * @author taoshihan
 * 
 */
public class Server {
    public static void main(String[] args) throws Exception {
        ServerSocket serverSocket = new ServerSocket(10004);
//        while (true) {
            Socket socket = serverSocket.accept();
            InputStream inputStream = socket.getInputStream();

            byte[] buf = new byte[1024];
            int len = inputStream.read(buf);

            InetAddress ip = socket.getInetAddress();
            
            System.out.println("来自" + ip.getHostAddress() + "说:"
                    + new String(buf, 0, len));
            Thread.sleep(10000);//睡眠10秒钟,客户端会一直等待
            OutputStream out=socket.getOutputStream();
            out.write("我是服务端,已经收到信息".getBytes());
            
            socket.close();
            serverSocket.close();
        //}
    }
}
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;

/**
 * 客户端
 * @author taoshihan
 *
 */
public class Client {
    public static void main(String[] args) throws Exception, IOException {
        Socket socket=new Socket(InetAddress.getLocalHost(), 10004);
        OutputStream outputStream=socket.getOutputStream();
        outputStream.write("我是客户端,服务端你好".getBytes());
        
        InputStream in=socket.getInputStream();
        byte[] b=new byte[1024];
        int len=in.read(b);//这里会阻塞,等待服务端的返回
        System.out.println(new String(b,0,len));
        socket.close();
    }
}

Client.java

原文地址:https://www.cnblogs.com/taoshihan/p/5548125.html