sa
积分: 17 注册: 2002-11-16 21:11:11
| import java.io.*; import java.net.*;
class socketListener implements Runnable { private Socket client; socketListener (Socket client) { this.client = client; } public void run(){ String line; try { BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream())); while(true) { line = in.readLine(); if (line!=null) System.out.println(line); } } catch (IOException e) { System.out.println("e.getMessage()"); System.exit(-1); } } }
public class socketTest { public void test(String host, int port) { String ss; try{ System.out.println("Establishing connection ..."); Socket socket = new Socket(host, port); PrintWriter out = new PrintWriter(socket.getOutputStream(), true); BufferedReader kbd = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Connection OK."); System.out.println("Start Listener ..."); socketListener sl = new socketListener(socket); Thread t = new Thread(sl); t.start(); System.out.println("Ready to accept input ..."); while (true) { ss = kbd.readLine(); out.println(ss); } } catch (IOException e) { System.out.println(e.getMessage()); System.exit(-1); }
}
public static void main(String[] args){
if (args.length < 2) { System.out.println("Usage: java socketTest <Host> <Port>"); System.exit(-1); } String host = args[0]; int port = Integer.parseInt(args[1], 10); System.out.println("Try to talk with: " + host + " at: " + port); socketTest test = new socketTest(); test.test(host, port); }
} __________________ ... 系统管理员 |