//MiniServer.java - server that echos what it receives 服务器端
import java.io.*;
import java.net.*;
class Server{
public static void main (String args[])
throws java.io.IOException
{ byte A[]=new byte[10];
if (args.length != 1) {
System.out.println("Usage: " +
"java MiniServer portnumber");
System.exit(1);
}
int portnum = Integer.parseInt(args[0]);
ServerSocket sock = null;
try {
sock = new ServerSocket(portnum);
}
catch (IOException e) {
System.out.println("不能监听端口: "
+ portnum + ", " + e);
System.exit(1);
}
System.out.println("正在监听端口 " +
portnum);
Socket clientSocket = null;
try {
clientSocket = sock.accept();
}
catch (IOException e) {
System.out.println("接收失败: " +
portnum + ", " + e);
System.exit(1);
}
BufferedReader input = new BufferedReader(
new InputStreamReader(
clientSocket.getInputStream()));
PrintWriter output =
new PrintWriter(clientSocket.getOutputStream());
System.out.println("连接存在.");
int i = 0;
String line = input.readLine();
System.in.read(A);
String link = new String(A);
while (link!=null) {
System.out.println(line);
i++;
output.println("line " + i + ":" + link);
output.flush();
System.in.read(A);
link= new String(A);
}
}
}
********************************************
//MiniClient.java - simple client for MiniServer 客户端
import java.io.*;
import java.net.*;
class Telnet{
public static void main (String args[])
throws java.io.IOException
{ byte b[]=new byte[10];
if (args.length != 2) {
System.out.println("提示: " +"使用 Telnet IP PortNum 来测试你的程序 如 Telnet 127.0.0.1 8080");
System.exit(0);
}
Socket sock= null;
int portnum = Integer.valueOf(args[1]).intValue();
try {
sock = new Socket(args[0], portnum);
}
catch (IOException e) {
System.out.println("不能连接: "+args[0]+":"+portnum + ", " + e);
System.exit(1);
}
BufferedReader input = new BufferedReader(
new InputStreamReader(sock.getInputStream()));
PrintWriter output =
new PrintWriter(sock.getOutputStream());
System.out.println("连接已经建立");
System.out.println("请输入讯息" +
" 并按回车:");
System.in.read(b);
String line = new String(b);
while (line != null) {
output.println(line);
output.flush();
line = input.readLine();
System.out.println("服务器返回讯息:" + line);
System.out.println("请输入讯息 " +
"并按回车:");
System.in.read(b);
line = new String(b);
}
}
}