电脑windows连接Socket的服务端:telnet localhost 1024
服务端
public class SocketServer {
public static void main(String[] args) {
ServerSocket serverSocket = null;
Map<String,Socket> CLENT_MAP = new HashMap<>();//用于存储连接进来的客户端
try{
//服务端ServerSocket 对象并指定端口号为 1024
serverSocket = new ServerSocket(1024);
System.out.println("服务已启动,等待客户端连接");
//连接多个客户端
while (true){
//客户端Socket对象
Socket socket = serverSocket.accept();//连接
//获取客户端连接的 IP 地址和端口号
String ip = socket.getInetAddress().getHostAddress();
System.out.println("有客户端连接ip:"+ ip +"端口:" + socket.getPort());
String clientKey = ip + socket.getPort();//ip+端口号
CLENT_MAP.put(clientKey,socket);//key:ip+端口号 value:客户端Socket对象
new Thread(()->{
while (true){
try{
//获取客户端发送的消息
InputStream inputStream = socket.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream,"utf8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String readData = bufferedReader.readLine();
System.out.println("收到客户端消息->" + readData);
//可以回复消息,谁发回谁
// OutputStream outputStream = socket.getOutputStream();
// PrintWriter printWriter = new PrintWriter(outputStream);
// printWriter.println("我是服务端,我已经收到了你发的消息" + readData);
// printWriter.flush();
CLENT_MAP.forEach((k,v)->{
try{
//获取发消息的对象
OutputStream outputStream = v.getOutputStream();
PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(outputStream,"utf8"));
printWriter.println(socket.getPort()+ ":" + readData);
printWriter.flush();
}catch (Exception e){
e.printStackTrace();
}
});
}catch (Exception e){
e.printStackTrace();
break;
}
}
}).start();
}
}catch (Exception e){
e.printStackTrace();
}
}
}
客户端
public class SocketClient {
public static void main(String[] args) {
Socket socket = null;
try{
//本地主连1024端口
socket = new Socket("127.0.0.1",1024);
OutputStream outputStream = socket.getOutputStream();
PrintWriter printWriter = new PrintWriter(outputStream);
System.out.println("请输入内容");
new Thread(()->{
while (true){
try{
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
try{
printWriter.println(input);
printWriter.flush();
}catch (Exception e){
e.printStackTrace();
break;
}
}catch (Exception e){
e.printStackTrace();
}
}
}).start();
//获取客户端发送的消息
InputStream inputStream = socket.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream,"utf8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
//接收回复的消息
new Thread(()->{
while (true){
try{
String readData = bufferedReader.readLine();
System.out.println("收到服务端消息->" + readData);
}catch (Exception e){
e.printStackTrace();
break;
}
}
}).start();
}catch (Exception e){
e.printStackTrace();
}
}
}
标签:printWriter,Socket,初体验,socket,println,new,客户端
From: https://blog.csdn.net/weixin_63164764/article/details/139652442