Client.java
class="java">
import java.io.*;
import java.net.*;
import java.util.*;
public class Client {
private String host;
private int port;
// 构造方法
public Client(String host,int port){
this.host=host;
this.port=port;
}
// 连接方法
public String connect(String msg){
if (msg == null) return null;
StringBuffer sb = new StringBuffer(100);
try {
Socket socket = new java.net.Socket(host,port);
PrintWriter writer = new java.io.PrintWriter(socket.getOutputStream(),true);
writer.println(msg);
try {
Scanner ins = new java.util.Scanner(socket.getInputStream());
while( ins.hasNextLine()){
sb.append(ins.nextLine());
}
} finally {
socket.close();
}
} catch(IOException e){
return e.toString();
}
return sb.toString();
}
// Test
public static void main(String[] args){
String msg =null;
if (args.length ==1){
msg = args[0];
} else {
System.out.println(" usage: java Clinet message ");
System.exit(1);
}
String host ="127.0.0.1";
int port = 12345;
Client client = new Client(host,port);
String str = client.connect(msg);
System.out.println(str);
}
}
运行 java Client message