一般服務器端代碼,每次收到一個線程,一個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();
}