[Java]簡單的Socket Client Server

這是一個超簡單的Client Server範例,Server部份利用Thread來常駐執行,而Client利用Socket去連接指定的port,送出一個字元組給OutputStream,而Server接收到請求後,使用InputStream來取得資料。

這裡有篇介紹Socket Server的原理Thread應用-Java SocketServer,還有一篇傳送物件Serializable序列化Socket傳送範例,這篇算是比較進階。

程式碼包裝在jar裡,利用二個command視窗,一個執行Server一個執行Client,結果如下:

Java Socket Client Server

原始碼及jar下載:


點我下載

主要的Server端程式碼

package test;
import java.net.ServerSocket;
import java.net.Socket;
public class SocketServer extends java.lang.Thread {
private boolean OutServer = false;
private ServerSocket server;
private final int ServerPort = 8765;// 要監控的port
public SocketServer() {
try {
server = new ServerSocket(ServerPort);
} catch (java.io.IOException e) {
System.out.println("Socket啟動有問題 !");
System.out.println("IOException :" + e.toString());
}
}
public void run() {
Socket socket;
java.io.BufferedInputStream in;
System.out.println("伺服器已啟動 !");
while (!OutServer) {
socket = null;
try {
synchronized (server) {
socket = server.accept();
}
System.out.println("取得連線 : InetAddress = "
+ socket.getInetAddress());
// TimeOut時間
socket.setSoTimeout(15000);
in = new java.io.BufferedInputStream(socket.getInputStream());
byte[] b = new byte[1024];
String data = "";
int length;
while ((length = in.read(b)) > 0)// <=0的話就是結束了
{
data += new String(b, 0, length);
}
System.out.println("我取得的值:" + data);
in.close();
in = null;
socket.close();
} catch (java.io.IOException e) {
System.out.println("Socket連線有問題 !");
System.out.println("IOException :" + e.toString());
}
}
}
public static void main(String args[]) {
(new SocketServer()).start();
}
}

Client端程式碼

package test;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.io.BufferedOutputStream;
public class SocketClient {
private String address = "127.0.0.1";// 連線的ip
private int port = 8765;// 連線的port
public SocketClient() {
Socket client = new Socket();
InetSocketAddress isa = new InetSocketAddress(this.address, this.port);
try {
client.connect(isa, 10000);
BufferedOutputStream out = new BufferedOutputStream(client
.getOutputStream());
// 送出字串
out.write("Send From Client ".getBytes());
out.flush();
out.close();
out = null;
client.close();
client = null;
} catch (java.io.IOException e) {
System.out.println("Socket連線有問題 !");
System.out.println("IOException :" + e.toString());
}
}
public static void main(String args[]) {
new SocketClient();
}
}

啟動Main

package test;
public class Main {
public static void main(String args[])
{
if(args.length==0)
System.out.println("請傳入參數server或client");
if(args[0].equals("server"))
(new SocketServer()).start();
else
new SocketClient();
}
}

3 thoughts to “[Java]簡單的Socket Client Server”

  1. 大大想請教您:
    如果我想傳遞的是一串16進位的bytes, 比如說 “03060038000039e6” 共8個bytes,取代”Send From Client “.getBytes() , 應該如何改寫? 網路上有一堆範例,您這個最接近我想要的,但就只差在傳遞的不是字串而是bytes? 找來找去改來改進總不正確,能否麻煩您修改一下,感謝!!

發表迴響