Java裡提供了ServerSocket與Socket類別,可將Client端的電腦連上伺服器,並可從伺服器傳遞資料給Client端。
Server端:
public class Server{
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
ServerSocket svs = new ServerSocket(5050); //建立ServerSocket物件,並設定埠號5050
System.out.println("waiting for client");
Socket sk = svs.accept(); //Client提出請求,accept()會傳回一個Socket物件,並讓sk指向它
System.out.println("Clinet connected");
while(sk.isConnected()){ //當Socket持續在連接時,就做下面的事
BufferedReader br = new BufferedReader(new InputStreamReader(sk.getInputStream()));
String msg=br.readLine();
if(msg==null){ //當Client disconnect時,readline會傳回null
break;
}
System.out.println(msg);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Client端:
public class Client {
public static void main(String[] args) {
// TODO Auto-generated method stub
BufferedWriter bw;
try {
Socket sk = new Socket("127.0.0.1",5050); //建立Socket物件,並設定ip(127.0.0.1是自己的主機)和埠號
System.out.println("已連線Server");
bw = new BufferedWriter(new OutputStreamWriter(sk.getOutputStream())); //利用sk來取得輸出串流
while(sk.isConnected()){
BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); //透過輸入串流來取得Client的輸入
System.out.print("client:");
bw.write("Client:"+br.readLine()+"\n"); //寫入輸出串流
bw.flush(); //立即傳送
}
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
PS:因為Server是在自己電腦執行,所以IP就是127.0.0.1
埠號使用者可以設定的只有1024~65535,0~1023為系統所保留
Server端
Client端
沒有留言:
張貼留言