1、可靠通信
TCP:Transmission Control Protocol传输控制协议
2、不可靠通信
UDP:User Datagram Protocol用户数据报协议
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(10000);
while(true) {
Socket client = serverSocket.accept();
InputStream in = client.getInputStream();
byte[] bytes = new byte[1024];
while(in.read(bytes) != -1 ) {
System.out.println(new String(bytes, "utf-8"));
}
}
}
编写服务器端socket
检查端口是否已监听:netstat -ano | findstr 10000
服务器实例化一个ServerSocket对象,就会监听这个端口,状态是LISTENING
3、客户端建立连接和服务端建立连接的关系(服务端端口10000 客户端端口50912)
(1)通过端口建立连接
建立连接
TCP 127.0.0.1:10000 127.0.0.1:50912 ESTABLISHED 6304
TCP 127.0.0.1:50912 127.0.0.1:10000 ESTABLISHED 6504
(2)通过端口加ip方式建立连接
服务器端的TCP连接
TCP 192.168.1.87:10000 192.168.1.23:63249 ESTABLISHED 392
客户端的TCP连接
TCP 192.168.1.23:63249 192.168.1.87:10000 ESTABLISHED 5608
4、客户端建立连接和服务端断开连接的关系
(1)客户端关闭输出流
服务器端TCP连接处于CLOSE_WAIT状态,客户端TCP连接进入FIN_WAIT_2状态
TCP 127.0.0.1:10000 127.0.0.1:50912 CLOSE_WAIT 6304
TCP 127.0.0.1:50912 127.0.0.1:10000 FIN_WAIT_2 6504
(2)服务器关闭输入流
服务器端TCP连接关闭,只剩下客户端TCP连接处于TIME_WAIT状态
TCP 127.0.0.1:51519 127.0.0.1:10000 TIME_WAIT 0
5、网络编程相关资源
https://www.toutiao.com/a6416949773957660930/?tt_from=android_share&utm_campaign=client_share×tamp=1532904633&app=news_article&iid=39063317945&utm_medium=toutiao_android
https://www.toutiao.com/a6518225380413800967/?tt_from=android_share&utm_campaign=client_share×tamp=1532904801&app=news_article&iid=39063317945&utm_medium=toutiao_android
https://www.toutiao.com/a6487080413918396942/?tt_from=android_share&utm_campaign=client_share×tamp=1532905563&app=news_article&iid=39063317945&utm_medium=toutiao_android
https://www.zhihu.com/question/30626103
https://blog.csdn.net/ma929226676/article/details/50970524
https://blog.csdn.net/BG_DATA/article/details/43668985
6、多线程 如:服务器端需要同时处理多个客户端连接
使用多线程,每个客户端请求过来会启动新线程
// 接受了客户端连接,启动新线程接收数据
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
InputStream in = null;
try {
in = socket.getInputStream();
byte[] bytes = new byte[1024];
while (in.read(bytes) != -1) {
System.out.println(new String(bytes, "utf-8"));
}
} catch(Exception ex) {
ex.printStackTrace();
} finally {
if(in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
thread.start();
7、使用线程池管理多个线程
private static Executor THREAD_POOL = Executors.newFixedThreadPool(50);
THREAD_POOL.execute(new Runnable() {
@Override
public void run() {
InputStream in = null;
try {
in = socket.getInputStream();
byte[] bytes = new byte[1024];
while (in.read(bytes) != -1) {
System.out.println(new String(bytes, "utf-8"));
}
} catch(Exception ex) {
ex.printStackTrace();
} finally {
if(in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
});