客户端服务端模型图
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/f2a0d0beaa8e90dbf9b30d97ed0a81bd.png)
实现服务端和客户端消息发送与接受
服务端
package com.qianfeng.xqc.day0317.socketwhile;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class DemoServiceWhile {
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(8888);
System.out.println("服务端启动...等待客户端连接...");
Socket service;
while(true) {
service = serverSocket.accept();
OutputStream os = service.getOutputStream();
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));
String msg = "你好客户端,我是服务端,你的ip:" + service.getInetAddress().getHostAddress() + "\n";
bw.write(msg);
bw.flush();
InputStream is = service.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String read = br.readLine();
System.out.println("客户端的消息:" + read);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
客户端
package com.qianfeng.xqc.day0317.socketwhile;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class DemoClientKeyInput {
public static void main(String[] args) {
String ip = "127.0.0.1";
int port = 8888;
try {
Socket client = new Socket(ip, port);
InputStream is = client.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String smsg = br.readLine();
System.out.println("服务器的消息:" + smsg);
String ss = shuru();
OutputStream os = client.getOutputStream();
String cmsg = ss + "你好服务端,我是客户端 \n";
os.write(cmsg.getBytes());
os.flush();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static String shuru() throws IOException {
InputStreamReader rd = new InputStreamReader(System.in);
BufferedReader sbr = new BufferedReader(rd);
System.out.println("请输入:");
String ss = sbr.readLine();
return ss;
}
}