tcp——IP
socket吧
全部回复
仅看楼主
level 1
domzhao2 楼主
import java.net.*;   // for Socket, ServerSocket, and InetAddress
import java.io.*;    // for IOException and Input/OutputStream
public class TCPEchoServer {
   private static final int BUFSIZE = 32;    // Size of receive buffer
   public static void main(String[] args) throws IOException {
     if (args.length != 1)   // Test for correct # of args
       throw new IllegalArgumentException("Parameter(s): <Port>");
     int servPort = Integer.parseInt(args[0]);
     // Create a server socket to accept client connection requests
     ServerSocket servSock = new ServerSocket(servPort);
     int recvMsgSize;    // Size of received message
     byte[] byteBuffer = new byte[BUFSIZE];   // Receive buffer
     for (;;) { // Run forever, accepting and servicing connections
       Socket clntSock = servSock.accept();      // Get client connection
       System.out.println("Handling client at " +
         clntSock.getInetAddress().getHostAddress() + " on port " +
              clntSock.getPort());
       InputStream in = clntSock.getInputStream();
       OutputStream out = clntSock.getOutputStream();
       // Receive until client closes connection, indicated by -1 return
       while ((recvMsgSize = in.read(byteBuffer)) != -1)
         out.write(byteBuffer, 0, recvMsgSize);
       clntSock.close();   // Close the socket.   We are done with this client!
     }
     /* NOT REACHED */
   }
}
import java.net.*;   // for DatagramSocket, DatagramPacket, and InetAddress
import java.io.*;    // for IOException
public class UDPEchoServer {
   private static final int ECHOMAX = 255;   // Maximum size of echo datagram
   public static void main(String[] args) throws IOException {
     if (args.length != 1)   // Test for correct argument list
       throw new IllegalArgumentException("Parameter(s): <Port>");
     int servPort = Integer.parseInt(args[0]);
     DatagramSocket socket = new DatagramSocket(servPort);
     DatagramPacket packet = new DatagramPacket(new byte[ECHOMAX], ECHOMAX);
     for (;;) {   // Run forever, receiving and echoing datagrams
       socket.receive(packet);      // Receive packet from client
       System.out.println("Handling client at " +
         packet.getAddress().getHostAddress() + " on port " + packet.getPort());
       socket.send(packet);        // Send the same packet back to client
       packet.setLength(ECHOMAX); // Reset length to avoid shrinking buffer
     }
     /* NOT REACHED */
   }
}
服务器总是不停地长时间运行,因此,它们必须设计为对客户端的任何行为都能提供好的服务。检查前面的服务器端示例程序(TCPEchoServer.java和UDPEchoServer.java),列出任何你能想到的能够导致服务器为其他客户端提供低效服务的客户端行为,并为修改这些问题提出建议。

2011年01月22日 14点01分 1
1