TCP/IP通信協(xié)議是一種可靠的網(wǎng)絡(luò)協(xié)議芹助,它在通信的兩端各建立一個Socket,從而在通信的兩端之間形成網(wǎng)絡(luò)虛擬鏈路。
一旦建立了虛擬網(wǎng)絡(luò)鏈路闲先,兩端的程序就可以通過虛擬鏈路進(jìn)行通信状土。Java對于TCP協(xié)議的網(wǎng)絡(luò)通信提供了良好的封裝,
Java使用Socket對象來達(dá)標(biāo)兩端的通信端口伺糠,并通過Socket產(chǎn)生IO流來進(jìn)行網(wǎng)絡(luò)通信蒙谓。
ServerSocket
Socket accept():如果接收到一個客戶端Socket的連接請求,該方法將返回一個與客戶端Socket對應(yīng)的Socket训桶;否則該
方法將一直處于等待狀態(tài)累驮。
ServerSocket(int port):用來指定的端口port(0~65535)來創(chuàng)建一個ServerSocket。
//創(chuàng)建一個ServerSocket舵揭,用于監(jiān)聽客戶端的Socket的連接請求
ServerSocket mServerSocket= new ServerSocket(3000);
//采用循環(huán)不斷地接收來自客戶端的請求
while (true){
//每當(dāng)接收到客戶端Socket的請求時谤专,服務(wù)端也對應(yīng)產(chǎn)生一個Socket
Socket mSocket=mServerSocket.accept();
}
Socket
Socket(InetAddress/Sting remoteAddress,int port):創(chuàng)建連接到指定遠(yuǎn)程主機(jī)、遠(yuǎn)程端口的Socket
//創(chuàng)建連接到本機(jī)午绳、3000端口的Socket
Socket mSocket= new Socket("127.0.0.1",3000);
IO流
InputStream getInputStream():返回該Socket對象對應(yīng)的輸入流置侍,讓程序通過該輸入流從Socket中取出數(shù)據(jù)
OutputStream getOutputStream():返回該Socket對象對應(yīng)的輸出流,讓程序通過該輸入流從Socket中取出數(shù)據(jù)
服務(wù)端:
//創(chuàng)建一個ServerSocket箱叁,用于監(jiān)聽客戶端的Socket的連接請求
ServerSocket mServerSocket= new ServerSocket(3000)墅垮;
while(true){
//每當(dāng)結(jié)束到客戶端Socket的請求時,服務(wù)端也對應(yīng)產(chǎn)生一個Soket
Socket mSocket=mServerSocket.accept();
//將Socket對飲的輸出流包裝成PrintStream
PrintStream ps=new PrintStream(mSocket.getInputStream());
ps.println("this is testing!");
ps.close();
mSocket.close();
}
客戶端:
Socket mSocket=new Socket("127.0.0.1" ,3000);
BufferedReader br = new BufferedReader(new InputStreamReader(mSocket.getInputStream());
//進(jìn)行普通IO操作
String line = br.readLine();
System.out.println("來自服務(wù)端的數(shù)據(jù):"+line);
br.close();
mSocket.close();
SocketClient&SocketServer
將socket客戶端封裝成SocketClient類耕漱,并提供connect(ip,port)算色、send()方法,通過接口類SocketListener來回掉onReceive( msg)螟够、onSend()接收發(fā)送的信息灾梦。關(guān)鍵代碼如下:
/**
* 連接服務(wù)端
* @param serverIp
* @param serverPort
*/
public void connect(final String serverIp, final int serverPort) {
// 開啟一個線程啟動tcp socket
new Thread(new Runnable() {
@Override
public void run() {
try {
byte[] buffer;
String msg;
mSocket = new Socket(serverIp, serverPort);
InputStream inStream = mSocket.getInputStream();
in = new BufferedReader(new InputStreamReader(mSocket.getInputStream()));
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
mSocket.getOutputStream())), true);
while (true) {
buffer = new byte[512];
if (mSocket.isConnected()) {
if (!mSocket.isInputShutdown()) {
// if ((content = in.readLine()) != null) {
// content += "\n";
// if (mSocketListener != null)
// mSocketListener.onReceive(content);
// }
if (inStream.read(buffer) != 0) {
msg = new String(buffer, "UTF-8").trim();
if (mSocketListener != null)
mSocketListener.onReceive(msg);
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
將socket服務(wù)端封裝成SocketServer類峡钓,并提供startServerSocket(serverPort),通過接口類SocketListener來回掉onReceive( msg)若河、onSend()接收發(fā)送的信息能岩。關(guān)鍵代碼如下:
public void startServerSocket(final int serverPort) {
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
try {
mServerSocket = new ServerSocket(serverPort);
mExecutorService = Executors.newCachedThreadPool();
while (true) {
socket = mServerSocket.accept();
mExecutorService.execute(new ReceiveThread(socket));
System.out.println("----connected success----");
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("UnknownHostException-->" + e.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("IOException" + e.toString());
}
}
}).start();
}
感謝以下文章提供的幫助:
Socket,你需要知道的事兒