Server/Client如何執行網路連接
import java.net.*;
import java.io.*;
public class Server11_4_1 {
public Server11_4_1() {
try{
ServerSocket SS = new ServerSocket(1234);
System.out.println("Server is created and waiting Client to connect...");
Socket socket = SS.accept();
System.out.println("connected from Client " + socket.getInetAddress());
socket.close();
}
catch(IOException e){
System.out.println(e.getMessage());
}
}
public static void main(String args[]){
Server11_4_1 ServerStart=new Server11_4_1();
}
}
ServerSocket(1234) 開啟一個通訊互閘, 為 1234 的 server port,
.accept() 等待 client 端連線過來,
連線成功就會顯示出發出訊號端的IP位置.
Server is created and waiting Client to connect...
connected from Client /140.121.198.91
-------------------------------------------------------------------------------------------
import java.io.*;
import java.net.*;
public class Client11_4_1 {
public Client11_4_1() {
try{
Socket socket = new Socket("IP", 1234);
socket.close();
}
catch(IOException e){
System.out.println(e.getMessage());
}
}
public static void main(String args[]) {
Client11_4_1 ClientStart=new Client11_4_1();
}
}
這裡就是Client 發送端的位置,
由 Socket 物件決定發送目地位置和通訊閘 編號.
沒有留言:
張貼留言