图解
1.server
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/07dbe3359c3c1a135adcf81e23e9dbb4.png)
2.client
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/09077c99e741806eb4ccb3c1c839578c.png)
3.总结
- 服务器开启端口,然后用accept等待其他的客户端用socket连接。
- 服务器和客户端发送消息可以使用字符和字符串。字符是InputStream和OutputStream,out是输出,in是接收。然后字符串是BufferedReader和PrintStream,read是接收,而print是输出。
- 记得用完关闭流。
- 我这里没考虑多线程的情况
代码部分
1.Server
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.stream.Stream;
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(5050);
Socket socket = serverSocket.accept();
InputStream is = null;
OutputStream os = null;
PrintStream ps = null;
BufferedReader br = null;
try {
ps = new PrintStream(socket.getOutputStream());
br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
ps.println("服务器发送的消息");
System.out.println("服务端收到:"+ br.readLine());
} catch (IOException e) {
System.out.println("出现异常");
} finally {
br.close();
ps.close();
socket.close();
serverSocket.close();
}
}
}
2.client
import java.io.*;
import java.net.Socket;
public class Client {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("127.0.0.1",5050);
InputStream is = null;
OutputStream os = null;
BufferedReader br = null;
PrintStream ps = null;
try {
br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
ps = new PrintStream(socket.getOutputStream());
System.out.println("客户端收到:"+ br.readLine());
ps.println("客户端发送的消息");
} catch (Exception e) {
System.out.println("出现异常");
} finally {
ps.close();
br.close();
socket.close();
}
}
}