Java Socket编程
多个客户同时连接
在实际的网络环境里,同一时间只对一个用户服务是不可行的。一个优秀的网络服务程序除了能处理用户的输入信息,还必须能够同时响应多个客户端的连接请求。在java中,实现以上功能特点是非常容易的。
设计原理:
主程序监听一端口,等待客户接入;同时构造一个线程类,准备接管会话。当一个Socket会话产生后,将这个会话交给线程处理,然后主程序继续监听。运用Thread类或Runnable接口来实现是不错的办法。
服务器
import java.io.*;
import java.net.*;
public class Server extends ServerSocket {
private static final int SERVER_PORT = 10000;
public Server() throws IOException {
super(SERVER_PORT);
try {
while (true) {
Socket socket = accept();
new CreateServerThread(socket);
}
} catch (IOException e) {}
finally {
close();
}
}
//--- CreateServerThread
class CreateServerThread extends Thread {
private Socket client;
private BufferedReader in;
private PrintWriter out;
public CreateServerThread(Socket s) throws IOException {
client = s;
in = new BufferedReader(new InputStreamReader(client.getInputStream(), "GB2312"));
out = new PrintWriter(client.getOutputStream(), true);
out.println("--- Welcome ---");
start();
}
public void run() {
try
{
String line = in.readLine();
while (!line.equals("bye")) {
String msg = createMessage(line);
out.println(msg);
line = in.readLine();
}
out.println("--- See you, bye! ---");
client.close();
} catch (IOException e) {}
}
private String createMessage(String line) {
xxxxxxxxx;
}
}
public static void main(String[] args) throws IOException {
new Server();
}
}
客户端
import java.io.*;
import java.net.*;
public class Client {
Socket socket;
BufferedReader in;
PrintWriter out;
public Client() {
try {
socket = new Socket("xxx.xxx.xxx.xxx", 10000);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(),true);
BufferedReader line = new BufferedReader(new InputStreamReader(System.in));
out.println(line.readLine());
line.close();
out.close();
in.close();
socket.close();
} catch (IOException e) {}
}
public static void main(String[] args) {
new Client();
}
}