简介
- 服务器监听端口
- 客户端与服务器建立连接
- 客户端发送数据请求
- 服务器业务逻辑处理
- 服务器返回信息
一、服务端
- 创建服务端口
- 开启服务
- 另起一个线程,轮询监听端口
- 开启处理客户端请求,轮询请处理求
ServerBoot.java
public class ServerBoot {
private static final int PORT = 8000;
public static void main(String[] args) {
Server server = new Server(PORT);
server.start();
}
}
Server.java
public class Server {
private ServerSocket serverSocket;
public Server(int port) {
try {
this.serverSocket = new ServerSocket(port);
System.out.println("服务器启动成功,端口:" + port);
} catch (IOException e) {
System.out.println("服务器启动失败");
}
}
public void start() {
new Thread(new Runnable() {
public void run() {
doStart();
}
}).start();
}
private void doStart() {
while (true) {
try {
Socket client = serverSocket.accept();
new ClientHandler(client).start();
} catch (IOException e) {
System.out.println("服务器端异常");
}
}
}
}
二、客户端
- 客户端启动
- 另起一个线程,客户端每5秒发送数据
Client.java
public class Client {
private static final String HOST = "127.0.0.1";
private static final int PORT = 8000;
private static final int SLEEP_TIME = 5000;
public static void main(String[] args) throws IOException {
final Socket socket = new Socket(HOST, PORT);
new Thread(new Runnable() {
public void run() {
System.out.println("客户端启动成功!");
while (true) {
try {
String message = "hello world";
System.out.println("客户端发送数据:" + message);
socket.getOutputStream().write(message.getBytes());
} catch (IOException e) {
System.out.println("写数据出错!");
e.printStackTrace();
}
sleep();
}
}
}).start();
}
private static void sleep() {
try {
Thread.sleep(SLEEP_TIME);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
三、运行
先启动服务器,再启动客户端