業務場景:現在有一個socket服務端給我們發送數據,我們需要建立一個socket Client來連接這個socket Server,然后接受server發送過來的數據。但是這個server可能會中斷,所以在Client要有一個while死循環去時刻保持與Server的連接。
package com.thinkgem.wlw.modules.test.socketdemo;
import java.io.*;
import java.net.Socket;
/**
* @Author zhouhe
* @Date 2019/10/14 17:41
*/
public class Client extends Thread{
//定義一個Socket對象
Socket socket = null;
private static String host = "192.168.0.109";
private static int port = 777;
public Client() {
try {
//需要服務器的IP地址和端口號,才能獲得正確的Socket對象
socket = new Socket(host, port);
} catch (Exception e) {
}
}
@Override
public void run() {
//客戶端一連接就可以寫數據個服務器了
super.run();
try {
// 讀Sock里面的數據
InputStream s = socket.getInputStream();
byte[] buf = new byte[1024];
int len = 0;
while ((len = s.read(buf)) != -1) {
System.out.println(new String(buf, 0, len));
}
} catch (Exception e) {
System.out.println("socket連接斷開!");
}
}
//函數入口
public static void main(String[] args) {
//需要服務器的正確的IP地址和端口號
while (true){
Client clientTest = new Client();
clientTest.start();
}
}
}
這里如果找不到socket Server,會報錯,一旦找到socket Server,就會自動連接,並且接受server發送過來的數據