1.包含客戶端和服務器兩部分程序,并且兩個程序能分開獨立運行。
2.客戶端可以輸入服務器地址和端口,連接服務器。
3..服務器能接受客戶端連接,并向客戶端輸出發送的字符串。

代碼如下:
服務器端:

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{
   //服務器在9999端口開辟了服務
   server=new ServerSocket(9999);
  }catch(Exception e){}
  //對于服務器而言,所有用戶的請求都是通過SeverSocket實現
  Socket client=null;
  try{
   //服務器在此等待用戶的鏈接
   System.out.println("等待客戶端鏈接、、、");
   client=server.accept();//服務端接收到一個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("客戶端回應完畢、、、");
 }

}


客戶端:

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{
   //實際上表示要鏈接到服務器上去了
   client=new Socket("192.168.1.23",9999);
  }catch(Exception e){}
  //等待服務器端的回應
  String str=null;
  //如果直接使用InputStream接受會比較麻煩
  //最好的方法是可以把內容放入發哦緩沖流之中進行讀取
  BufferedReader buf=null;
  
  try{
   buf=new BufferedReader(new InputStreamReader(client.getInputStream()));
      str=buf.readLine();
  }catch(Exception e){}
  System.out.println(str);
 }

}