一般服务器端代码,每次收到一个线程,一个client就会产生:
/************************ 开始监听 **************************/
int port = 4311;
ServerSocket server = null;//服务器
Socket client = null;//客户端
try {
server = new ServerSocket(port);
} catch (IndirectionException e1) {
System.out.println("正在监听...");
}
while(true)
{
System.out.println("等待客户"+i);
i++;
try {
client = server.accept();//开始监听线程,接收到client
System.out.println("客户地址:" + client.getInetAddress());
} catch (IOException e1) {
System.out.println("正在等待客户");
}
}
客户端代码,启动之后便会连接服务器,得到回应之后便会形成socket连接
Socket clientsocket = null;
try {
clientsocket = new Socket("localhost",4311);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
(责任编辑:城市网)