`

j2se-10.13-log

阅读更多

2006.10.13      晴
      网络编程,知道了编程是在OSI中的表示层,而套接字Socket则是在传输层中的概念,其中的ServerSocket,Socket重点内容,因为在网络编程当中几乎都要使用到它们,端口(0-65535)分为三类:公认端口(0-1023),注册端口(1024-49151),动态或私有端口(49152-65535).
   还是看个例子吧!
   先看Server端的:
package com.softeem.socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;

public class TestServer {

 private static final String QUIT = "quit";

 public void startServer() {
  try {
   ServerSocket listener = new ServerSocket(1234);
   Socket ss = listener.accept();
   BufferedReader serverIn = new BufferedReader(new InputStreamReader(
     ss.getInputStream()));
   PrintStream serverOut = new PrintStream(ss.getOutputStream());

   serverOut.println("Welcome to the test server");
   System.out.println(serverIn.readLine());

   String fromClientInfo = null;
   while ((fromClientInfo = serverIn.readLine()) != null) {
    System.out.println(fromClientInfo);
    if (QUIT.equalsIgnoreCase(fromClientInfo)) {
     System.exit(0);
    }
   }
   serverOut.close();
   serverIn.close();
   ss.close();
  } catch (IOException e) {
   e.printStackTrace();
  }

 }

 /**
  * @param args
  */
 public static void main(String[] args) {
  TestServer server = new TestServer();
  server.startServer();
 }

}
再看看client端的:
package com.softeem.socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;

public class TestClient {

 private static final String QUIT = "quit";
 public void startClient(){
  
  try {
   Socket cs = new Socket("localhost",1234);
   BufferedReader in  = new  BufferedReader(new InputStreamReader(System.in));
   BufferedReader clientIn  = new  BufferedReader(new InputStreamReader(cs.getInputStream()));
   PrintStream clientOut = new PrintStream(cs.getOutputStream());
   
   System.out.println(clientIn.readLine());
   clientOut.println("hello i am here");
   System.out.println("Please send some string to server");
   
   String toServerInfo = null;
   while( (toServerInfo = in.readLine())!= null){
    clientOut.println(toServerInfo);
    if (QUIT.equalsIgnoreCase(toServerInfo)){
     System.exit(0);
    }
   }
   
   clientIn.close();
   clientOut.close();
   cs.close();
  } catch (UnknownHostException e) {
   e.printStackTrace();
  } catch (IOException e) {

   e.printStackTrace();
  }
  
 }
 /**
  * @param args
  */
 public static void main(String[] args) {
  TestClient  client = new TestClient();
  client.startClient();
 }
}

分享到:
评论
发表评论

文章已被作者锁定,不允许评论。

相关推荐

Global site tag (gtag.js) - Google Analytics