网络编程基础-bio

master
bingor 3 years ago
commit 4d810fc5b9

@ -0,0 +1,35 @@
package com.msb.io.bio;/**
* @Author bingor
* @Date 2022/10/19 14:59
* @Description: com.msb.bio
* @Version: 1.0
*/
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
/**
*@ClassName Client
*@Description TODO
*@Author bingor
*@Date 2022/10/19 14:59
*@Version 3.0
*/
public class Client {
public static void main(String[] args) {
try {
Socket socket = new Socket("127.0.0.1", 8888);
OutputStream os = socket.getOutputStream();
os.write("hello server".getBytes());
os.flush();
System.out.println("write over, waiting for msg back...");
byte[] bytes = new byte[1024];
int len = socket.getInputStream().read(bytes);
System.out.println(new String(bytes, 0, len));
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

@ -0,0 +1,49 @@
package com.msb.io.bio;/**
* @Author bingor
* @Date 2022/10/19 15:11
* @Description: com.msb.bio
* @Version: 1.0
*/
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
/**
*@ClassName Server
*@Description TODO
*@Author bingor
*@Date 2022/10/19 15:11
*@Version 3.0
*/
public class Server {
public static void main(String[] args) {
try {
ServerSocket server = new ServerSocket();
server.bind(new InetSocketAddress("127.0.0.1", 8888));
while (true) {
Socket socket = server.accept(); //阻塞方法
new Thread(() -> {
handle(socket);
}).start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void handle(Socket socket) {
byte[] bytes = new byte[1024];
try {
int len = socket.getInputStream().read(bytes);
System.out.println(new String(bytes, 0, len));
socket.getOutputStream().write("hello client".getBytes());
socket.getOutputStream().flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Loading…
Cancel
Save