Java學習-Java socket應用的幾個小實例

用於本機上的客護端與服務器對話的小程序:

  客護端:

  import java.io.BufferedReader;

  import java.io.BufferedWriter;

  import java.io.InputStreamReader;

  import java.io.OutputStreamWriter;

  import java.net.Socket;

  public class Client extends Thread

  {

  public void Write() throws Exception

  {

  Socket s=new Socket(“127.0.0.1″,12345);

  BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));

  BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

  String message=”客護端說:”;

  while(!(message.equals(“”)))

  {

  message=br.readLine();

  System.out.println(“客護端說:”+message);

  bw.write(message+”\n”);

  bw.flush();

  }

  bw.close();

  s.close();

  }

  public void run()

  {

  Socket m=null;

  BufferedReader dr=null;

  try

  {

  m=new Socket(“127.0.0.1″,12345);

  dr=new BufferedReader(new InputStreamReader(m.getInputStream()));

  String msg=”服務器說:”;

  while(!(msg.equals(“”)))

  {

  msg=dr.readLine();

  System.out.println(“服務器說:”+msg);

  }

  }

  catch(Exception e){e.printStackTrace();}

  finally

  {

  try

  {

  dr.close();

  m.close();

  }

  catch(Exception e){e.printStackTrace();}

  }

  }

  public static void main(String args[])throws Exception

  {

  Client c=new Client();

  c.start();

  c.Write();

  }

  }

  服務器:

  import java.io.BufferedReader;

  import java.io.BufferedWriter;

  import java.io.InputStreamReader;

  import java.io.OutputStreamWriter;

  import java.net.ServerSocket;

  import java.net.Socket;

  public class Server extends Thread

  {

  private ServerSocket ss=null;

  public Server ()throws Exception

  {

  ss=new ServerSocket(12345);

  }