客户端代码如下:


package com.gloomyfish.socket.tutorial.two;

import java.io.DataInputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;

public class HelloClient {
 private int clientNumber;
 private SocketAddress address;
 public HelloClient(int clientNum) {
  clientNumber = clientNum;
 }
 
 public void setupClients(String serverHostName, int port) throws IOException {
  address = new InetSocketAddress(serverHostName, port);
  for(int i=0; i<clientNumber; i++) {
   System.out.println();
   System.out.println("start client No. " + (i+1));
   Socket socket = new Socket();
   socket.connect(address);
   DataInputStream bufferedReader = new DataInputStream(socket.getInputStream());
   byte[] cbuff = new byte[256];
   char[] charBuff = new char[256];
   int size = 0;
   while( (size = bufferedReader.read(cbuff))> 0) {
    convertByteToChar(cbuff, charBuff, size);
    System.out.println(charBuff);
   }
   bufferedReader.close();
   socket.close();
  }
 }
 
 private void convertByteToChar(byte[] cbuff, char[] charBuff, int size) {
  for(int i=0; i<charBuff.length; i++) {
   if(i < size) {
    charBuff[i] = (char)cbuff[i];
   } else {
    charBuff[i] = ' ';
   }
  }
 
 }

 public static void main(String[] args) {
  try {
   HelloClient client = new HelloClient(10);
   client.setupClients("localhost", 9999);
  } catch (IOException e) {
   e.printStackTrace();
  }
 }
}
  启动10个客户端去连接服务器端,接受到服务器端问候以后客户端关闭连接。

  特别提示:一定要初始化缓冲区charBuff

  程序运行结果: