Java 实现TCP Socket简单通信

194 阅读1分钟

Java实现socket编程,本文主要从 server 和 client 的信息收发简单实现。

Server

package org.example;

import java.io.DataInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 单收信息server
 */
public class SimpleSocketServer {
    public static void main(String[] args) throws IOException {
        System.out.println("------Server------");

        // 1.指定端口
        ServerSocket server = new ServerSocket(8000);
        // 2.阻塞式等待连接
        Socket so = server.accept();
        System.out.println("有客户端正在连接...");
        // 3.IO操作
        DataInputStream dis = new DataInputStream(so.getInputStream());
        String content = dis.readUTF();
        System.out.println("读取内容:" + content);
        // 4.释放连接
        dis.close();
        so.close();

        server.close();
    }
}

Client

package org.example;

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

/**
 * 单发信息client
 */
public class SimpleSocketClient {
    public static void main(String[] args) throws IOException {
        System.out.println("---Client---");
        // 1.建立连接
        Socket client = new Socket("localhost", 8000);
        // 2.IO操作
        DataOutputStream dos = new DataOutputStream(client.getOutputStream());
        dos.writeUTF("Hello, server!");
        dos.flush();

        // 3.释放连接
        dos.close();
        client.close();
    }
}