伺服器通訊篇(Socket)
阿新 • • 發佈:2018-12-20
文章目錄
簡介
- 伺服器監聽埠
- 客戶端與伺服器建立連線
- 客戶端傳送資料請求
- 伺服器業務邏輯處理
- 伺服器返回資訊
一、服務端
- 建立服務埠
- 開啟服務
- 另起一個執行緒,輪詢監聽埠
- 開啟處理客戶端請求,輪詢請處理求
ServerBoot.java
public class ServerBoot {
private static final int PORT = 8000;
public static void main(String[] args) {
Server server = new Server(PORT) ;
server.start();
}
}
Server.java
public class Server {
private ServerSocket serverSocket;
public Server(int port) {
try {
this.serverSocket = new ServerSocket(port);
System.out.println("伺服器啟動成功,埠:" + port);
} catch (IOException e) {
System.out.println("伺服器啟動失敗");
}
}
public void start() {
new Thread(new Runnable() {
public void run() {
doStart();
}
}).start();
}
private void doStart() {
while (true) {
try {
Socket client = serverSocket.accept();
new ClientHandler(client).start();
} catch (IOException e) {
System.out.println("伺服器端異常");
}
}
}
}
二、客戶端
- 客戶端啟動
- 另起一個執行緒,客戶端每5秒傳送資料
Client.java
public class Client {
private static final String HOST = "127.0.0.1";
private static final int PORT = 8000;
private static final int SLEEP_TIME = 5000;
public static void main(String[] args) throws IOException {
final Socket socket = new Socket(HOST, PORT);
new Thread(new Runnable() {
public void run() {
System.out.println("客戶端啟動成功!");
while (true) {
try {
String message = "hello world";
System.out.println("客戶端傳送資料:" + message);
socket.getOutputStream().write(message.getBytes());
} catch (IOException e) {
System.out.println("寫資料出錯!");
e.printStackTrace();
}
sleep();
}
}
}).start();
}
private static void sleep() {
try {
Thread.sleep(SLEEP_TIME);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
三、執行
先啟動伺服器,再啟動客戶端