4.1、Address already in use : JVM_Bind
【Socket】三、Socket使用線程池支持多個線程同時訪問
首先玩這個需要知道本機IP地址,那麼,Windows + R - > CMD ->輸入命令 ipconfig
如圖找到IP地址
一、配置Socket端口號與IP地址
public class SocketConfig {
/** IP地址,每臺主機IP都不同,請修改 */
public static final String IP_ADDRESS = "192.168.**.***";
/** 端口號 */
public static final Integer PORT = 8088;
}
二、UDP協議
2.1、 UDP服務端類
public class UdpServer {
public static void main(String[] args) throws IOException {
System.out.println("udp接受數據啓動.......");
DatagramSocket ds = new DatagramSocket(SocketConfig.PORT);
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf, buf.length);
// 阻塞效果
ds.receive(dp);
System.out.println("來源:" + dp.getAddress().getHostAddress() + ",port:" + dp.getPort());
String str = new String(dp.getData(),0,dp.getLength());
System.out.println("客戶端發送數據:"+str);
ds.close();
}
}
2.2、UDP客戶端類
public class UdpClient {
public static void main(String[] args) throws IOException {
System.out.println("udp 發送數據");
DatagramSocket ds = new DatagramSocket();
String str = "客戶端發送數據....";
byte[] strByte = str.getBytes();
DatagramPacket dp = new DatagramPacket(strByte,
strByte.length, InetAddress.getByName(SocketConfig.IP_ADDRESS),
SocketConfig.PORT
);
ds.send(dp);
ds.close();
}
}
2.3、運行結果
2.4、UDP說明
QQ使用的協議即是UDP,不管接受者是否在線,信息也會發送過去。不管連不連接。
且UDP協議與TCP服務是不互通的,也就是說通過UDP協議開啓的端口瀏覽器是訪問不到的。
但TCP可以做到,因爲HTTP默認TCP。 PS:UDP協議毫無反應
以下即是TCP協議通過瀏覽器訪問後打印的數據,雖然頁面是無展示,但服務器會有數據
三、TCP協議
3.1、服務端類
public class TcpServer {
public static void main(String[] args) throws IOException {
System.out.println("socket服務器端啓動....");
ServerSocket serverSocket = new ServerSocket(SocketConfig.PORT);
//獲取客戶端對象
Socket accept = serverSocket.accept();
InputStream inputStream = accept.getInputStream();
byte[] buf= new byte[1024];
int len=inputStream.read(buf);
String str =new String(buf,0,len);
System.out.println("str:" + str);
serverSocket.close();
}
}
3.2、客戶端類
public class TcpClinet {
public static void main(String[] args) throws IOException {
System.out.println("socket啓動....");
Socket s = new Socket(SocketConfig.IP_ADDRESS, SocketConfig.PORT);
OutputStream outputStream = s.getOutputStream();
outputStream.write("我是客戶端....".getBytes());
s.close();
}
}
3.3、運行結果
3.4、三次握手與四次分手
3.4.1 三次握手
來一個流程圖
3.4.2 四次分手
四次分手的傳遞過程其實就是三次握手的過程的一個反轉,這裏就不詳細說明。PS:自行腦補 /手動滑稽
3.5、使用場景
HTTP協議即是TCP協議
四、網絡通訊容易遇到的BUG
4.1、Address already in use : JVM_Bind
將TCP協議服務的端口改爲一個已使用的端口,比如說8080,或者是開兩個服務使用一樣的端口,即會出現該錯誤,Tomcat端口號佔用即是如此
4.2、Connection refused:connet
在不開啓TCP服務類時,開啓TCP客戶端即會拋出該異常
該錯誤意思爲連接被拒絕,有兩種原因:
1.、連接超時
2、連接端口並未開啓,或已經關閉 (當前演示的是這個原因)