一个Scocket实例程序(Java)

ZDNet软件频道 时间:2001-08-14 作者: |  我要评论()
本文关键词:Java
一个简单的Scocket实例程序
转载自Java开发者

//EchoServer1.java

import Java.io.*;
import Java.net.*;

public class EchoServer1
{ public static void main(String[] args )
{ try
{
ServerSocket s = new ServerSocket(8500);
Socket incoming = s.accept( );
BufferedReader in = new BufferedReader
(new InputStreamReader(incoming.getInputStream()));
PrintWriter out = new PrintWriter
(incoming.getOutputStream(), true /* autoFlush */);

out.println( "Hello! Enter BYE to exit." );

boolean done = false;
while (!done)
{ String line = in.readLine();
if (line == null) done = true;
else
{ out.println("Echo: " + line);

if (line.trim().equals("BYE"))
done = true;
}
}
incoming.close();
}
catch (Exception e)
{ System.out.println(e);
}
}
}


// EchoClient1.java
import Java.io.*;
import Java.net.*;

public class EchoClient1 {     
 public static void main(String args[])   {
   try{
      if (args.length != 1){
System.out.println("USAGE: Java Client servername");
return;
      }
      String  connectto= args[0];
      Socket connection;
      // connect to server
      if(connectto.equals("localhost")){
connection=new Socket(InetAddress.getLocalHost(),8500);
      }
      else{
connection=new Socket(InetAddress.getByName(connectto),8500);
      }
      BufferedReader  input=new BufferedReader(new InputStreamReader(connection.getInputStream()));                      
      PrintWriter out = new PrintWriter(connection.getOutputStream(), true /* autoFlush */);

      // read information from server                       
      String info;
      info = input.readLine();
      System.out.println(info);
      boolean done = false;
      BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
      String sInput;
      while(!done){
         sInput = in.readLine();
         out.println(sInput);
         if (sInput.equalsIgnoreCase("bye")) done = true;                          
         info = input.readLine();                          
         System.out.println(info);
     }
     connection.close();                                                              
   }
   catch(SecurityException e){
     System.out.println("SecurityException when connecting Server!");
   }
   catch(IOException e){
     System.out.println("IOException when connecting Server!");  
   }
 }
}

运行
1 运行服务器
  Java EchoServer1
2 运行 客户端
  Java EchoClient1 server_hostname 
 



百度大联盟认证黄金会员Copyright© 1997- CNET Networks 版权所有。 ZDNet 是CNET Networks公司注册服务商标。
中华人民共和国电信与信息服务业务经营许可证编号:京ICP证010391号 京ICP备09041801号-159
京公网安备:1101082134