一個 HelloWord 級別的 Java Socket 通信的例子通訊過程
先啟動 Server 端進入一個死循環以便一直監聽某端口是否有連接請求然後運行 Client 端客戶端發出連接請求服務端監聽到這次請求後向客戶端發回接受消息連接建立啟動一個線程去處理這次請求然後繼續死循環監聽其他請求客戶端輸入字符串後按回車鍵向服務器發送數據服務器讀取數據後回復客戶端數據這次請求處理完畢啟動的線程消亡如果客戶端接收到 OK 之外的返回數據會再次發送連接請求並發送數據服務器會為這次連接再次啟動一個線程來進行響應…直到當客戶端接收到的返回數據為 OK 時客戶端退出
服務端源代碼
[java] view plaincopyprint?
package comdefondssocketbegin;
import javaioBufferedReader;
import javaioDataInputStream;
import javaioDataOutputStream;
import javaioInputStreamReader;
import ServerSocket;
import Socket;
public class Server {
public static final int PORT = ;//監聽的端口號
public static void main(String[] args) {
Systemoutprintln(服務器啟動…\n)
Server server = new Server()
serverinit()
}
public void init() {
try {
ServerSocket serverSocket = new ServerSocket(PORT)
while (true) {
// 一旦有堵塞 則表示服務器與客戶端獲得了連接
Socket client = serverSocketaccept()
// 處理這次連接
new HandlerThread(client)
}
} catch (Exception e) {
Systemoutprintln(服務器異常 + egetMessage())
}
}
private class HandlerThread implements Runnable {
private Socket socket;
public HandlerThread(Socket client) {
socket = client;
new Thread(this)start()
}
public void run() {
try {
// 讀取客戶端數據
DataInputStream input = new DataInputStream(socketgetInputStream())
String clientInputStr = inputreadUTF()//這裡要注意和客戶端輸出流的寫方法對應否則會拋 EOFException
// 處理客戶端數據
Systemoutprintln(客戶端發過來的內容 + clientInputStr)
// 向客戶端回復信息
DataOutputStream out = new DataOutputStream(socketgetOutputStream())
Systemoutprint(請輸入\t)
// 發送鍵盤輸入的一行
String s = new BufferedReader(new InputStreamReader(Systemin))readLine()
outwriteUTF(s)
outclose()
inputclose()
} catch (Exception e) {
Systemoutprintln(服務器 run 異常 + egetMessage())
} finally {
if (socket != null) {
try {
socketclose()
} catch (Exception e) {
socket = null;
Systemoutprintln(服務端 finally 異常 + egetMessage())
}
}
}
}
}
}
package comdefondssocketbegin;
import javaioBufferedReader;
import javaioDataInputStream;
import javaioDataOutputStream;
import javaioInputStreamReader;
import ServerSocket;
import Socket;
public class Server {
public static final int PORT = ;//監聽的端口號
public static void main(String[] args) {
Systemoutprintln(服務器啟動…\n)
Server server = new Server()
serverinit()
}
public void init() {
try {
ServerSocket serverSocket = new ServerSocket(PORT)
while (true) {
// 一旦有堵塞 則表示服務器與客戶端獲得了連接
Socket client = serverSocketaccept()
// 處理這次連接
new HandlerThread(client)
}
} catch (Exception e) {
Systemoutprintln(服務器異常 + egetMessage())
}
}
private class HandlerThread implements Runnable {
private Socket socket;
public HandlerThread(Socket client) {
socket = client;
new Thread(this)start()
}
public void run() {
try {
// 讀取客戶端數據
DataInputStream input = new DataInputStream(socketgetInputStream())
String clientInputStr = inputreadUTF()//這裡要注意和客戶端輸出流的寫方法對應否則會拋 EOFException
// 處理客戶端數據
Systemoutprintln(客戶端發過來的內容 + clientInputStr)
// 向客戶端回復信息
DataOutputStream out = new DataOutputStream(socketgetOutputStream())
Systemoutprint(請輸入\t)
// 發送鍵盤輸入的一行
String s = new BufferedReader(new InputStreamReader(Systemin))readLine()
outwriteUTF(s)
outclose()
inputclose()
} catch (Exception e) {
Systemoutprintln(服務器 run 異常 + egetMessage())
} finally {
if (socket != null) {
try {
socketclose()
} catch (Exception e) {
socket = null;
Systemoutprintln(服務端 finally 異常 + egetMessage())
}
}
}
}
}
} 客戶端源代碼
[java] view plaincopyprint?
package comdefondssocketbegin;
import javaioBufferedReader;
import javaioDataInputStream;
import javaioDataOutputStream;
import javaioIOException;
import javaioInputStreamReader;
import Socket;
public class Client {
public static final String IP_ADDR = localhost;//服務器地址
public static final int PORT = ;//服務器端口號
public static void main(String[] args) {
Systemoutprintln(客戶端啟動…)
Systemoutprintln(當接收到服務器端字符為 \OK\ 的時候 客戶端將終止\n)
while (true) {
Socket socket = null;
try {
//創建一個流套接字並將其連接到指定主機上的指定端口號
socket = new Socket(IP_ADDR PORT)
//讀取服務器端數據
DataInputStream input = new DataInputStream(socketgetInputStream())
//向服務器端發送數據
DataOutputStream out = new DataOutputStream(socketgetOutputStream())
Systemoutprint(請輸入 \t)
String str = new BufferedReader(new InputStreamReader(Systemin))readLine()
outwriteUTF(str)
String ret = inputreadUTF()
Systemoutprintln(服務器端返回過來的是 + ret)
// 如接收到 OK 則斷開連接
if (OKequals(ret)) {
Systemoutprintln(客戶端將關閉連接)
Threadsleep()
break;
}
outclose()
inputclose()
} catch (Exception e) {
Systemoutprintln(客戶端異常 + egetMessage())
} finally {
if (socket != null) {
try {
socketclose()
} catch (IOException e) {
socket = null;
Systemoutprintln(客戶端 finally 異常 + egetMessage())
}
}
}
}
}
}
package comdefondssocketbegin;
import javaioBufferedReader;
import javaioDataInputStream;
import javaioDataOutputStream;
import javaioIOException;
import javaioInputStreamReader;
import Socket;
public class Client {
public static final String IP_ADDR = localhost;//服務器地址
public static final int PORT = ;//服務器端口號
public static void main(String[] args) {
Systemoutprintln(客戶端啟動…)
Systemoutprintln(當接收到服務器端字符為 \OK\ 的時候 客戶端將終止\n)
while (true) {
Socket socket = null;
try {
//創建一個流套接字並將其連接到指定主機上的指定端口號
socket = new Socket(IP_ADDR PORT)
//讀取服務器端數據
DataInputStream input = new DataInputStream(socketgetInputStream())
//向服務器端發送數據
DataOutputStream out = new DataOutputStream(socketgetOutputStream())
Systemoutprint(請輸入 \t)
String str = new BufferedReader(new InputStreamReader(Systemin))readLine()
outwriteUTF(str)
String ret = inputreadUTF()
Systemoutprintln(服務器端返回過來的是 + ret)
// 如接收到 OK 則斷開連接
if (OKequals(ret)) {
Systemoutprintln(客戶端將關閉連接)
Threadsleep()
break;
}
outclose()
inputclose()
} catch (Exception e) {
Systemoutprintln(客戶端異常 + egetMessage())
} finally {
if (socket != null) {
try {
socketclose()
} catch (IOException e) {
socket = null;
Systemoutprintln(客戶端 finally 異常 + egetMessage())
}
}
}
}
}
}
注意 Socket 輸出流寫數據方法是 writeUTF 時輸入流讀取相關數據要用 readUTF否則會拋 EOFException 異常具體原因請參考文後鏈接
From:http://tw.wingwit.com/Article/program/Java/hx/201311/25568.html