package _11_socket;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import lombok.SneakyThrows;
public class _01_TCPSocket
{
public static void main(String[] args)
{
new Thread(() -> startServer()).start();
new Thread(() -> startClient()).start();
}
@SneakyThrows
private static void startServer()
{
ServerSocket server_socket = new ServerSocket(8080);
System.out.println("server start");
// 接收来自多个客户端的连接
while (Boolean.parseBoolean("true"))
{
Thread.currentThread().sleep(1000);
Socket client_socket = server_socket.accept();
System.out.println("connection build");
new Thread(() -> handleConnection(client_socket)).start();
}
server_socket.close();
}
@SneakyThrows
private static void handleConnection(Socket client_socket)
{
DataOutputStream dos = new DataOutputStream(client_socket.getOutputStream());
dos.writeUTF("请问要点什么?");
dos.flush();
System.out.println("server: 请问要点什么?");
DataInputStream dis = new DataInputStream(client_socket.getInputStream());
// readUTF()是个阻塞方法,会一直等待数据
dis.readUTF();
dos.writeUTF("对不起,没有鱼丸!");
dos.flush();
System.out.println("server: 对不起,没有鱼丸!");
dis.readUTF();
dos.writeUTF("对不起,没有粗面!");
dos.flush();
System.out.println("server: 对不起,没有粗面!");
dis.readUTF();
dos.writeUTF("......");
dos.flush();
System.out.println("server: ......");
client_socket.shutdownOutput();
}
@SneakyThrows
private static void startClient()
{
Socket client_socket = new Socket("localhost", 8080);
System.out.println("client start");
DataInputStream dis = new DataInputStream(client_socket.getInputStream());
dis.readUTF();
DataOutputStream dos = new DataOutputStream(client_socket.getOutputStream());
dos.writeUTF("来碗鱼丸");
dos.flush();
System.out.println("client: 来碗鱼丸");
dis.readUTF();
dos.writeUTF("来碗粗面");
dos.flush();
System.out.println("client: 来碗粗面");
dis.readUTF();
dos.writeUTF("那就来碗鱼丸粗面吧!");
dos.flush();
System.out.println("client: 那就来碗鱼丸粗面吧!");
client_socket.shutdownInput();
client_socket.close();
}
}
【Java】【网络编程】Socket
关注
打赏