只实现了回显功能,就是客户端发什么过来,服务端就将原数据返回.其中的处理是一线程对应一个客户端
服务端:
public class TcpServer {
public static void main(String[] args) throws Exception{
if (args.length!=1){
throw new IllegalArgumentException("Parameter(s):<Port>");
}
int echoServPort=Integer.parseInt(args[0]);
ServerSocket servSocket=new ServerSocket(echoServPort);
Logger logger=Logger.getLogger("practical");
Executor service= Executors.newFixedThreadPool(5);
while (true){
Socket socket=servSocket.accept();
service.execute(new TcpHandler(socket,logger));
}
}
}
服务端处理请求类:
public class TcpHandler implements Runnable {
private static final int BUFSIZE = 32;
private static int TIMELIMIT=10000;
private Socket socket;
private Logger logger;
public TcpHandler(Socket socket, Logger logger) {
this.socket=socket;
this.logger=logger;
}
public static void handleClient(Socket socket, Logger logger) {
try {
InputStream in=socket.getInputStream();
OutputStream out=socket.getOutputStream();
int recvMsgSize;
int totalBytesEchoed=0;
byte[] receiveBuf=new byte[BUFSIZE];
long endTime=System.currentTimeMillis()+TIMELIMIT;
int timeBoundMillis=TIMELIMIT;
socket.setSoTimeout(timeBoundMillis);
//Receive until client closes connection,indicate by -1
while ((timeBoundMillis > 0) && ((recvMsgSize = in.read(receiveBuf)) != -1)) {
out.write(receiveBuf, 0, recvMsgSize);
totalBytesEchoed += recvMsgSize;
timeBoundMillis = (int) (endTime - System.currentTimeMillis()) ;
socket.setSoTimeout(timeBoundMillis);
}
logger.info("Client " + socket.getRemoteSocketAddress() + ", received " + totalBytesEchoed + " bytes.");
}catch (IOException e){
logger.log(Level.WARNING, "Exception in echo protocol", e);
}finally {
try {
socket.close();
}catch (IOException e){
}
}
}
@Override
public void run() {
handleClient(socket, logger);
}
}
客户端:
public class TcpClient {
public static void main(String[] args) throws IOException{
if (args.length != 3) { // Test for correct # of args
throw new IllegalArgumentException("Parameter(s): <Server> <Port> <Data>");
}
String destAddr = args[0]; // Destination address
int destPort = Integer.parseInt(args[1]); // Destination port
byte[] data = args[2].getBytes();// Data
Socket socket = new Socket(destAddr, destPort);
OutputStream out = socket.getOutputStream();
out.write(data); // Send the encoded string to the server
// Receive the same string back from the server
InputStream in = socket.getInputStream();
int totalBytesRcvd = 0; // Total bytes received so far
int bytesRcvd; // Bytes received in last read
while (totalBytesRcvd < data.length) {
if ((bytesRcvd = in.read(data, totalBytesRcvd,data.length - totalBytesRcvd)) != -1){
totalBytesRcvd += bytesRcvd;
}
} // data array is full
System.out.println("Received: " + new String(data));
socket.close();
}
}