2.客戶端可以輸入服務(wù)器地址和端口,連接服務(wù)器。
3..服務(wù)器能接受客戶端連接,并向客戶端輸出發(fā)送的字符串。
代碼如下:
服務(wù)器端:
package com.dr.Demo01;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
public class ServerSocket01 {
public static void main(String[] args) {
ServerSocket server=null;
try{
//服務(wù)器在9999端口開辟了服務(wù)
server=new ServerSocket(9999);
}catch(Exception e){}
//對(duì)于服務(wù)器而言,所有用戶的請(qǐng)求都是通過SeverSocket實(shí)現(xiàn)
Socket client=null;
try{
//服務(wù)器在此等待用戶的鏈接
System.out.println("等待客戶端鏈接、、、");
client=server.accept();//服務(wù)端接收到一個(gè)client
}catch(Exception e){}
//要向客戶端打印信息
PrintStream out=null;
//得到向客戶端輸出信息的能力
try{
out=new PrintStream(client.getOutputStream());
}catch(Exception e){}
out.println("Hi,how do you do?");
try{
client.close();
server.close();
}catch(Exception e){}
System.out.println("客戶端回應(yīng)完畢、、、");
}
}
客戶端:
package com.dr.Demo01;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.Socket;
public class ClientSocket01 {
public static void main(String[] args) {
Socket client=null;
try{
//實(shí)際上表示要鏈接到服務(wù)器上去了
client=new Socket("192.168.1.23",9999);
}catch(Exception e){}
//等待服務(wù)器端的回應(yīng)
String str=null;
//如果直接使用InputStream接受會(huì)比較麻煩
//最好的方法是可以把內(nèi)容放入發(fā)哦緩沖流之中進(jìn)行讀取
BufferedReader buf=null;
try{
buf=new BufferedReader(new InputStreamReader(client.getInputStream()));
str=buf.readLine();
}catch(Exception e){}
System.out.println(str);
}
}