java网络编程TCP字节流,接受并返回数据

TCP建立客户端和服务器

端口设置为不常用的,防止端口被占用;
这里ip为本机ip,自己发送自己接收。
注:先开启服务端再开客户端发送数据。

客户端代码如下:

//字节流,客户端
public class TCPClient {
    public static void main(String[] args) {
        //发送的字符串
        String message = "访问成功\n";
        //这是本机ip
        String serverAddress = "192.168.43.4";
        //端口
        int port = 9998;
        try {
            //新建Socket对象
            Socket socket = new Socket(serverAddress,port);
            //创建字节输出流
            OutputStream os = socket.getOutputStream();
            //写入数据,将字符串转换成字节
            os.write(message.getBytes());
            //创建字节输出流
            InputStream is = socket.getInputStream();
            //建立字节数组存放读取的数据
            byte[] b = new byte[1024];
            int len = is.read(b);
            System.out.println(new String(b,0,len));
            //关闭资源
            is.close();
            os.close();
            socket.shutdownOutput();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

服务端:

//字节流,服务端
public class TCPServer {
    public static void main(String[] args) {
        int port = 9998;
        String message = "回复成功\n";
        try {
            //创建 ServerSocket对象,绑定端口,开始等待连接
            ServerSocket serverSocket = new ServerSocket(port);
            //设置监听,接收连接accept方法,返回socket对象.
            Socket socket = serverSocket.accept();

            InputStream is = socket.getInputStream();
            byte[] b = new byte[1024];
            int len = is.read(b);
            System.out.println(new String(b,0,len));

            OutputStream os = socket.getOutputStream();
            os.write(message.getBytes());
            //关闭资源
            is.close();
            os.close();
            socket.close();
            serverSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

你可能感兴趣的:(java,网络编程)