socket通訊原理以及實現
阿新 • • 發佈:2019-01-07
服務端
package com.hmsm.socket.server;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
/**
* 模擬查詢天氣
* Socket 服務端
* @author Administrator
*
*/
public class SocketServer {
public static void main(String[] args) throws IOException {
//啟動socket服務端
ServerSocket serverSocket=new ServerSocket(55555);
System.out.println("服務端已啟動。。。");
DataInputStream inputStream=null;
DataOutputStream outputStream=null;
while(true){
try {
//監聽客戶端連線 accept()是阻塞方法
Socket socket= serverSocket.accept();
//先接收從客戶端傳送過來的資料
inputStream=new DataInputStream(socket.getInputStream()) ;
//城市名稱
String cityName=inputStream.readUTF();
//接收客戶端傳送過來的城市名稱
System.out.println("from client。。。"+cityName);
//再通過服務端傳送出去
outputStream=new DataOutputStream(socket.getOutputStream());
String result="晴轉陰" ;
//將查詢結果傳送出去
outputStream.writeUTF(result);
System.out.println("to client。。。"+result);
} catch (Exception e) {
e.printStackTrace();
}finally{
if(inputStream!=null){
inputStream.close();
}
if(outputStream!=null){
outputStream.close();
}
}
}
}
}
客戶端
package com.hmsm.socket.client;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
/**
* 模擬查詢天氣
* Socket 客戶端
* @author Administrator
*
*/
public class SocketClient {
public static void main(String[] args) throws UnknownHostException, IOException {
//建立Socket連線
Socket socket=new Socket("127.0.0.1",55555);
DataInputStream inputStream=null;
DataOutputStream outputStream=null;
try {
//傳送資料
outputStream=new DataOutputStream(socket.getOutputStream());
String cityName="成都";
outputStream.writeUTF(cityName);
System.out.println("to server。。。"+cityName);
//接收資料
inputStream=new DataInputStream(socket.getInputStream());
String result=inputStream.readUTF();
System.out.println("from server。。。"+result);
} catch (Exception e) {
e.printStackTrace();
}finally{
if(outputStream!=null){
outputStream.close();
}
if(inputStream!=null){
inputStream.close();
}
if(socket!=null){
socket.close();
}
}
}
}