客户端代码
public class TCPEchoClient {
public static void main(String [] args) throws UnknownHostException, IOException, InterruptedException {
if(args.length<2||args.length>3){
throw new IllegalArgumentException("Parameter(s):<Server> <Word> [<Port>]");
}
String server=args[0];
byte [] data=args[1].getBytes();
int servPort=(args.length==3)?Integer.parseInt(args[2]):7;
//1.创建一个Socket实例:构造函数向指定的远程主机和端口建立一个TCP连接
Socket socket=new Socket(server,servPort);
System.out.println("Connected to server... sending echo string");
/**
*2. 通过套接字的输入输出流进行通信:一个Socket连接实例包括一个InputStream和一个OutputStream,它们的用法同于其他Java输入输出流。
*/
InputStream in=socket.getInputStream();
OutputStream out=socket.getOutputStream();
out.write(data);
int totalBytesRcvd=0;
int bytesRcvd;
while(totalBytesRcvd<data.length){
if((bytesRcvd=in.read(data, totalBytesRcvd, data.length-totalBytesRcvd))==-1){
throw new SocketException("Connection closed prematurely");
}
totalBytesRcvd+=bytesRcvd;
}
System.out.println("Receved: "+new String(data));
//3.使用Socet类的close()方法关闭连接
socket.close();
}
}
服务端代码
public class TCPEchoServer {
private static final int BUFSIZE=32;
public static void main(String [] args) throws IOException, InterruptedException{
if(args.length!=1){
throw new IllegalArgumentException("Parameter(s):<Port>");
}
int servPort=Integer.parseInt(args[0]);
//1.创建一个ServerSocket实例并制定本地端口。此套接字的功能是侦听该制定端口收到的连接。
ServerSocket servSock=new ServerSocket(servPort);
int recvMsgSize;
byte [] receiveBuf=new byte[BUFSIZE];
//2.重复执行
while(true){
//a.调用ServerSocket的accept()方法以获取下一个客户端连接。
//基于新建立的客户端连接,创建一个Socket实例,并由accept()方法返回
Socket clntSock=servSock.accept();
SocketAddress clientAddress=clntSock.getRemoteSocketAddress();
System.out.println("Handling client at "+clientAddress);
//b,使用所返回的Socket实例的InputStream和OutputStream与客户端进行通信
InputStream in=clntSock.getInputStream();
OutputStream out=clntSock.getOutputStream();
while((recvMsgSize=in.read(receiveBuf))!=-1){
out.write(receiveBuf, 0, recvMsgSize);
}
//c,通信完成后,使用Socket的close()方法关闭该客户端套接字链接
clntSock.close();
}
}
}