Socket编程

来源:互联网 发布:网络协议分析pdf 编辑:程序博客网 时间:2024/06/10 12:00

服务器端:TcpServer

import java.io.*;
import java.net.*;

public class TcpServer {

 public static void main(String[] args) {

  ServerSocket svrsoc = null;
  Socket soc = null;
  DataInputStream in = null;
  PrintStream out = null;
  InetAddress clientIP = null;
  String str = null;

  try {

   svrsoc = new ServerSocket(1234);
   soc = svrsoc.accept();
   in = new DataInputStream(soc.getInputStream());
   out  = new PrintStream(soc.getOutputStream());

   clientIP = soc.getInetAddress();
   System.out.println("Client's IP address: " + clientIP);
   out.println("Welcome!...");
   str = in.readLine();
   while(!str.equals("quit")) {

    System.out.println("Client said: " + str);
    str = in.readLine();

   }
   System.out.println("Client want to leave.");

  }catch(Exception e) {

   System.out.println("Error: " + e);

  }

 }

}

 客户端:TcpClient

import java.net.*;
import java.io.*;

public class TcpClient {

 public static void main(String[] args) {

  Socket soc = null;
  BufferedReader in = null;
  PrintWriter out  = null;
  String strin = null;
  String strout = null;

  try {

   soc = new Socket("localhost",1234);
   System.out.println("Connecting to Server...");
   in = new BufferedReader(new InputStreamReader(soc.getInputStream()));
   out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(soc.getOutputStream())),true);
   strin = in.readLine();
   System.out.println("Server said: " + strin);
   byte bmsg[] = new byte[20];
   System.in.read(bmsg);
   String msg = new String(bmsg,0);
   msg = msg.trim();
   while(!msg.equals("quit")) {

    out.println(msg);
    System.in.read(bmsg);
    msg = new String(bmsg,0);
    msg = msg.trim();
    out.println(msg);
    
   }
   out.println(strout);

  }catch(Exception e) {
  
   System.out.println("Errer: " + e);

  }
  finally {
   
   try{

   in.close();
   out.close();
   soc.close();
   System.exit(0);

   }catch(Exception e){

    System.out.println("Error: " + e);

   }

  }

 }

}

先运行服务器端,再运行客户段。

这个例子很简单,而且有缺陷,但原理上是这样。

原创粉丝点击