日期:2014-05-20  浏览次数:20783 次

socket客户端连接异常
问一个socket server的问题,我现在是可以多条client连接Server,,一般是先连接,然后发送数据,,但是我现在出现的问题是当一个client连接Server的时候只连接上但不发送数据,这时候其它的client也进不来了,,想问下有没有好的思路啊,,

------解决方案--------------------
ServerSocket 监听的线程,除了 accept() 不要做别的事,给每个连入的 Socket 单独分配一个线程。为了共享状态,使用相同的逻辑对待所有连入的 Socket,可以用 inner class,比如下面这样的设计:

Java code

import java.io.IOException;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public abstract class SocketServer implements Runnable {
  
  public static void main(String[] args) throws Exception {
    
    SocketServer server = new SocketServer(4321) {

      @Override
      protected void serve(Socket socket) {
        
        try {
          
          PrintStream ps = new PrintStream(socket.getOutputStream());
          ps.println("Hello!");
          ps.flush();
          ps.close();
          socket.close();
        }
        catch(IOException ex) {
          
          ex.printStackTrace();
        }
      }
    };
    
    server.start();
    
    // ...
  }
  
  private final int port;
  private volatile boolean runFlag;
  private ExecutorService executor;
  public SocketServer(int port) {
    
    this.port = port;
  }
  
  @Override
  public void run() {
    
    ServerSocket ss = null;
    try {
      
      ss = new ServerSocket(port);
      runFlag = true;
      while( runFlag ) {
        
        Socket socket = ss.accept();
        if( runFlag )
          getExecutor().submit(new Connection(socket));
      }
    }
    catch(IOException ex) {
      
      throw new RuntimeException(ex);
    }
    finally {
      
      try {
        
        if( ss != null )
          ss.close();
      }
      catch(Exception e) {
        
        // log exception
      }
    }
  }
  
  public void start() {
    
    getExecutor().submit(this);
  }
  
  public void stop() {
    
    runFlag = false;
    
    try {
      
      new Socket("127.0.0.1", port).close();
    }
    catch(IOException ex) {
      
      // not important
    }
  }
  
  protected abstract void serve(Socket socket);
  
  protected ExecutorService getExecutor() {
    
    if( executor == null )
      executor = Executors.newCachedThreadPool();
    return executor;
  }
  
  private class Connection implements Runnable {
    
    private final Socket socket;
    private Connection(Socket socket) {
      
      this.socket = socket;
    }

    @Override
    public void run() {
      
      serve(socket);
    }
  }
}

------解决方案--------------------
先去了解下阻塞式IO和异步式IO(NIO)