三,socket通信
1.http://blog.csdn.net/kongxx/article/details/7288896这个人写的关于socket通信不错,循序渐进式的讲解,用代码示例说明,运用流和socket进行远程通讯

2.最简单的socket是一个服务端对应一个客户端
 server的写法

  1. ServerSocket server = new ServerSocket();
  2. Socket socket = server.accept();
  3. BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
  4. PrintWriter out = new PrintWriter(socket.getOutputStream());
  5. while (true) {
  6. String msg = in.readLine();
  7. System.out.println(msg);
  8. out.println("Server received " + msg);
  9. out.flush();
  10. if (msg.equals("bye")) {
  11. break;
  12. }
  13. }
  14. socket.close();

);

  • BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
  • PrintWriter out = new PrintWriter(socket.getOutputStream());
  • BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
  • while (true) {
  • String msg = reader.readLine();
  • out.println(msg);
  • out.flush();
  • if (msg.equals("bye")) {
  • break;
  • }
  • System.out.println(in.readLine());
  • }
  • socket.close();
  • );

  • os = new ObjectOutputStream(socket.getOutputStream());
  • User user = new User("user_" + i, "password_" + i);
  • os.writeObject(user);
  • os.flush();
  • is = new ObjectInputStream(new BufferedInputStream(socket.getInputStream()));
  • Object obj = is.readObject();
  • if (obj != null) {
  • user = (User)obj;
  • System.out.println("user: " + user.getName() + "/" + user.getPassword());
  • }
  • } catch(IOException ex) {
  • );

  • socket.connect(socketAddress,  * );
  • socket.setSoTimeout( * );
  • gzipos = new GZIPOutputStream(socket.getOutputStream());
  • oos = new ObjectOutputStream(gzipos);
  • User user = new User("user_" + i, "password_" + i);
  • oos.writeObject(user);
  • oos.flush();
  • gzipos.finish();
  • gzipis = new GZIPInputStream(socket.getInputStream());
  • ois = new ObjectInputStream(gzipis);
  • Object obj = ois.readObject();
  • if (obj != null) {
  • user = (User)obj;
  • System.out.println("user: " + user.getName() + "/" + user.getPassword());
  • }
  • } catch(IOException ex) {
  • );

    );

    ));

  • serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
  • while (selector.select() > ) {
  • Iterator<SelectionKey> it = selector.selectedKeys().iterator();
  • while (it.hasNext()) {
  • SelectionKey readyKey = it.next();
  • it.remove();
  • execute((ServerSocketChannel) readyKey.channel());  
    1. private static void execute(ServerSocketChannel serverSocketChannel) throws IOException {
    2. SocketChannel socketChannel = null;
    3. try {
    4. socketChannel = serverSocketChannel.accept();
    5. MyRequestObject myRequestObject = receiveData(socketChannel);
    6. logger.log(Level.INFO, myRequestObject.toString());
    7. MyResponseObject myResponseObject = new MyResponseObject(
    8. "response for " + myRequestObject.getName(),
    9. "response for " + myRequestObject.getValue());
    10. sendData(socketChannel, myResponseObject);

    1. MyRequestObject myRequestObject = null;
    2. ByteArrayOutputStream baos = new ByteArrayOutputStream();
    3. ByteBuffer buffer = ByteBuffer.allocate();
    4. try {
    5. byte[] bytes;
    6. int size = ;
    7. while ((size = socketChannel.read(buffer)) >= ) {
    8. buffer.flip();
    9. bytes = new byte[size];
    10. buffer.get(bytes);
    11. baos.write(bytes);
    12. buffer.clear();
    13. }
    14. bytes = baos.toByteArray();
    15. Object obj = SerializableUtil.toObject(bytes);
    16. myRequestObject = (MyRequestObject)obj;

    1. sendData(SocketChannel socketChannel, MyResponseObject myResponseObject) throws IOException {
    2. byte[] bytes = SerializableUtil.toBytes(myResponseObject);
    3. ByteBuffer buffer = ByteBuffer.wrap(bytes);
    4. socketChannel.write(buffer);
  • client的写法

    1. socketChannel = SocketChannel.open();
    2. SocketAddress socketAddress = new InetSocketAddress("localhost", );
    3. socketChannel.connect(socketAddress);
    4. MyRequestObject myRequestObject = new MyRequestObject("request_" + idx, "request_" + idx);
    5. logger.log(Level.INFO, myRequestObject.toString());
    6. sendData(socketChannel, myRequestObject);
    7. MyResponseObject myResponseObject = receiveData(socketChannel);
    8. logger.log(Level.INFO, myResponseObject.toString());
    1. private void sendData(SocketChannel socketChannel, MyRequestObject myRequestObject) throws IOException {
    2. byte[] bytes = SerializableUtil.toBytes(myRequestObject);
    3. ByteBuffer buffer = ByteBuffer.wrap(bytes);
    4. socketChannel.write(buffer);
    5. socketChannel.socket().shutdownOutput();
      1. private MyResponseObject receiveData(SocketChannel socketChannel) throws IOException {
      2. MyResponseObject myResponseObject = null;
      3. ByteArrayOutputStream baos = new ByteArrayOutputStream();
      4. try {
      5. ByteBuffer buffer = ByteBuffer.allocateDirect();
      6. byte[] bytes;
      7. int count = ;
      8. while ((count = socketChannel.read(buffer)) >= ) {
      9. buffer.flip();
      10. bytes = new byte[count];
      11. buffer.get(bytes);
      12. baos.write(bytes);
      13. buffer.clear();
      14. }
      15. bytes = baos.toByteArray();
      16. Object obj = SerializableUtil.toObject(bytes);
      17. myResponseObject = (MyResponseObject) obj;
      18. socketChannel.socket().shutdownInput();

      return myResponseObject;

    上面的例子都需要先运行server再运行client。