ServerSocket 监听端口,通过accept 方法返回一个 Socket实例,通过socket 拿到输入输出流,输入流用来读客户端发送过来的流数据,输出流用来把服务端数据返回到客户端的。
思考:服务端的socket 和客户端的socket 不是同一个,却能从同一个流里面写数据、拿数据,是怎么样做到的。
编写服务端代码:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
/**
* SOCKET服务端
*/
public class Main {
public static void main(String[] args) {
/** 监听端口 */
int port = 8080;
/** 建立套接字, 获取IO流 */
Socket bridge = null;
/** 从bridge中读客户端写入的流数据 */
BufferedReader reader = null;
try {
System.out.println("正在监听端口:" + port);
ServerSocket serverSocket = new ServerSocket(port);
while (true) {
/** accept阻塞队列, 监听客户端的请求 */
bridge = serverSocket.accept();
reader = new BufferedReader(new InputStreamReader(bridge.getInputStream()));
/** 遍历流数据 while 条件不要用 null != reader.readLine() ,这样的话第一行数据读不到 */
String body = reader.readLine();
while (body != null) {
System.out.println("服务端接收消息: " + body);
body = reader.readLine();
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (null != reader) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
reader = null;
}
if (null != bridge) {
try {
bridge.close();
} catch (IOException e) {
e.printStackTrace();
}
bridge = null;
}
}
}
}
编写客户端代码
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.Socket;
public class Main {
private static final String IP = "127.0.0.1";
private static final Integer PORT = 8080;
public static void main(String[] args) {
Socket client = null;
BufferedWriter writer = null;
for (int i = 0; i < 1; i++) {
try {
client = new Socket(IP, PORT);
writer = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
writer.write("Hello! 我是" + Thread.currentThread().getName());
} catch (IOException e) {
e.printStackTrace();
} finally {
if (null != writer) {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
writer = null;
}
if (null != client) {
try {
client.close();
} catch (IOException e) {
e.printStackTrace();
}
client = null;
}
}
}
}
}