首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

Java Socket 的一个范例程序

2012-12-23 
Java Socket 的一个实例程序Java通过TCP协议的通信的编程都是通过Socket ,不会很难,一般通用的就是下面这

Java Socket 的一个实例程序
Java通过TCP协议的通信的编程都是通过Socket ,不会很难,一般通用的就是下面这个小例子。大概就能了解Socket的编程方法了。

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

public class EchoServer {
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);
  }
}
}



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

public class EchoClient {
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!");
  }
}
}

热点排行