import java.net.*;
import java.io.*;
/**
* <p>Title: 簡單服務器服務端</p>
* <p>Description: 這是一個簡單的服務器端程序</p>
* <p>Copyright: Copyright (c) 2003</p>
* <p>Filename: SampleServer.java</p>
* @version 1.0
*/
public class SampleServer{
public static void main(String[] arges){
try{
int port = 8888;
//使用8888端口創建一個ServerSocket
ServerSocket mySocket = new ServerSocket(port);
//等待監聽是否有客戶端連接
Socket sk = mySocket.accept();
//輸入緩存
BufferedReader in = new BufferedReader (
new InputStreamReader (sk.getInputStream ()));
//輸出緩存
PrintWriter out = new PrintWriter (
new BufferedWriter(
new OutputStreamWriter(
sk.getOutputStream ())), true);
//打印接收到的客戶端發送過來的信息
System.out.println("客戶端信息:"+in.readLine ());
//向客戶端回信息
out.println("你好,我是服務器。我使用的端口號: "+port);
}catch(Exception e){
System.out.println(e);
}
}
}
import java.io.*;
import java.net.*;
/**
* <p>Title: 簡單服務器客戶端</p>
* <p>Description: 本程序是一個簡單的客戶端,用來和服務器連接</p>
* <p>Copyright: Copyright (c) 2003</p>
* <p>Filename: SampleClient.java</p>
* @version 1.0
*/
public class SampleClient{
public static void main(String[] arges){
try{
//獲取一個IP。null表示本機
InetAddress addr = InetAddress.getByName(null);
//打開8888端口,與服務器建立連接
Socket sk = new Socket (addr, 8888);
//緩存輸入
BufferedReader in = new BufferedReader (
new InputStreamReader (sk.getInputStream ()));
//緩存輸出
PrintWriter out = new PrintWriter (
new BufferedWriter(
new OutputStreamWriter(
sk.getOutputStream ())), true);
//向服務器發送信息
out.println ("你好!");
//接收服務器信息
System.out.println (in.readLine ());
}catch(Exception e){
System.out.println(e);
}
}
}