Socket又称套接字 ,套接字使用TCP提供了两台计算机之间的通信机制,客户端程序创建一个Socket,并尝试连接服务器的Socket,当连接建立时客户端和服务器现在可以通过对 Socket 对象的写入和读取来进行通信,java为服务器提供了一种监听客户端并与他们建立连接的机制。聊天室本质上就是输入输出流
第一步:搭建服务端,直接上代码
ServerSocket serverSocket=new ServerSocket(8080);
System.out.println("服务器等待客户端连接");
//无客户端接入是,此方法阻塞
Socket accept = serverSocket.accept();
System.err.println("客户端连接上服务器");
new Thread(new Runnable() {//开启子线程发送消息给客户端
@Override
public void run() {
while (true){
Scanner scanner=new Scanner(System.in);
String message = scanner.next();
try {
OutputStream outputStream = accept.getOutputStream();
PrintStream printStream = new PrintStream(outputStream);
printStream.println(message);
printStream.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}).start();
while (true){//循环监听
//此方法会阻塞当前线程,监听输入流
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(accept.getInputStream()));
System.err.println("客户端消息---》"+bufferedReader.readLine());
}
第二步:搭建客户端
//连接本地8080端口
Socket socket=new Socket("127.0.0.1",8080);
OutputStream out = null;
PrintStream printStream = null;
System.err.println("成功连接上服务器");
new Thread(new Runnable() {//开启子线程接收服务器消息
@Override
public void run() {
while (true){
InputStream in = null;
try {
in = socket.getInputStream();//此方法会阻塞当前线程
} catch (IOException e) {
e.printStackTrace();
}
Scanner scanner = new Scanner(in);
System.err.println("服务端-->" + scanner.nextLine());
}
}
}).start();
while (true){//主线程发送消息
Scanner scanner=new Scanner(System.in);
String next = scanner.next();
if (next.equals("退出")){
socket.close();
if (out!=null){
out.close();
}
if (printStream!=null){
printStream.close();
}
}
out=socket.getOutputStream();
printStream=new PrintStream(out);
printStream.println(next);
printStream.flush();
}
第三步:测试,先启动服务端,再启动客户端