`
孤独舞者
  • 浏览: 85921 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

java 中socket与tcp udp

    博客分类:
  • java
阅读更多
转载来自:http://lzkyo.iteye.com/blog/455855
前几天在本区看到一个贴子,有人问,在Socket做服务器,在手机上用Http访问,如何实现。这个贴子,有十来个人回复了,可惜回复的都是:Socket使用TCP/IP协议,客户端用HTTP协议,不同协议不可能实现通讯。再可惜,那个贴子结了,要不然,我就可以回复了!在这里拿出来说一下,让大家不要再误会了(TCP/IP与HTTP不可通讯) 
  因为目前很多手机仍不支持MIDP2.0,只支持MIDP1.0,而Socket技术只在MIDP2.0才提供支持,所以,一般的Java   ME程序的如果要实现C/S结构,都会选用Tomcat等服务器、sevlet或JavaBean等Java   EE架构实现。不过,考虑到响应速度与性能的问题,Tomcat等Java   EE架构可能满足不了业务要求,这样,我们就要用到下面将要说的自已写服务器的技术了。       
  一般的C/S结构程序,一般程序员都会写,不过,这里一般程序员刚接触Socket写服务器,Http写客户端都会头大——不可能吧,Socket用TCP/IP协议,客户端用Http协议,不同协议间,怎么可能通讯呢!       
  本文要说的就是这个问题了。       
  大家一定都知道,网络系统一共分7层,在这七层中,Http协议要高于TCP/IP协议(因为在互联网中,计算机是通过IP定位的,也就是用TCP/IP 协议了),对网络操作系统有了解的人,一定不会忘记,我们用Http访问www的时候,用的是域名,而域名,最终还是要通过DNS转换成IP地址的。这就对了——HTTP协议基于TCP/IP协议!而Socket正是基于TCP/IP协议,这样一来,它们就有了共同之外了!有了以上的认识,理论方面就没问题了。       
  我们再讨论一下实现:       
  服务器:       
  和一般的C/S结构一样,用Socket(java中用ServerSocket)监听。监听、读写消息的方面与一般的C/S服务器一模一样。不同的是,考虑到客户端只支持http协议,所以,读客户端消息的时候,读到的将是http头+消息,那么,我们便要用程序分析并去掉http头,只用消息。发消息的时候正好相反,在发送的消息前面,自己加上http头(其实就是一个包含一定内容的字符串),这样再发出去,客户端就可以收到并读取了。   
  客户端:       
  用Http连接,在java中,用的是HttpConnection.open("http://"+IP+":"+Port)访问服务器,这样,就可以向ServerSocket请求连接了。       
  在open之后,再向HttpConnection对象的输出流写入消息,然后刷新流再关闭HttpConnection就可以了,客户端因为本来用的就是http协议,所以不用自行加http头,底层会处理的;服务器在Accept()之后,就可以从Socket的输入流读到消息了。当然,如果要读服务器的消息的话,可以在HttpConnection关闭前读它的输入流(读的时候,如果还没有收到服务器消息,会阻塞当前线程的,直到读到为止,不怕读不到)。客户端读到的消息,是不包括http头的,所以,也就不用我们自行处理了。   
  要注意的是,HttpConnetion.open后,只能用一次,刷新后,它就无效了,得重新调用open方法再次建立连接。(服务器最好使用线程建立Socket与客户端连接,连接一次一个线程。) 


Java代码

   1. 服务器示例代码:(共三个类)    
   2.   //HttpServer.java    
   3.   package   testnetserver;    
   4.      
   5.   public   class   HttpServer{    
   6.   public   HttpServer()   {    
   7.   }    
   8.   public   static   void   main(String[]   aregs){    
   9.   HttpServerSocket   hss=new   HttpServerSocket();    
  10.   hss.start();    
  11.   }    
  12.   }    
  13.      
  14.      
  15.      
  16.      
  17.      
  18.      
  19.   //HttpServerSocket.java    
  20.   package   testnetserver;    
  21.      
  22.   import   java.net.ServerSocket;    
  23.   import   java.io.*;    
  24.      
  25.   public   class   HttpServerSocket   extends   Thread{    
  26.   ServerSocket   ss=null;    
  27.   private   static   final   int   port=2222;    
  28.   public   HttpServerSocket()   {    
  29.   }    
  30.   public   void   run(){    
  31.   try   {    
  32.   ss   =   new   ServerSocket(port);    
  33.   }    
  34.   catch   (IOException   ex)   {    
  35.   System.out.println("ServerSocket   can   not   listen");    
  36.   System.out.println("Error   on   ServerSocket   bind   port");    
  37.   ex.printStackTrace();    
  38.   ss=null;    
  39.   return;    
  40.   }    
  41.   //循环监听    
  42.   while(true){    
  43.   HttpSocket   hs=null;    
  44.   try   {    
  45.   hs=new   HttpSocket();    
  46.   hs.s=ss.accept();    
  47.   System.out.println("have   a   client   connect");    
  48.   hs.start();    
  49.   }    
  50.   catch   (IOException   ex1)   {    
  51.   System.out.println("Error   on   accept");    
  52.   }    
  53.   }    
  54.   }    
  55.   }    
  56.      
  57.      
  58.      
  59.      
  60.      
  61.      
  62.   //HttpSocket.java    
  63.   package   testnetserver;    
  64.      
  65.   import   java.net.Socket;    
  66.   import   java.io.*;    
  67.      
  68.   public   class   HttpSocket    
  69.   extends   Thread   {    
  70.   public   Socket   s   =   null;    
  71.   String   msg   =   "";    
  72.   public   HttpSocket()   {    
  73.   }    
  74.      
  75.   public   void   run()   {    
  76.   BufferedReader   is   =   null;    
  77.   PrintWriter   os   =   null;    
  78.   try   {    
  79.   //由Socket对象得到输入流,并构造相应的BufferedReader对象    
  80.   is   =   new   BufferedReader(new   InputStreamReader(s.getInputStream()));    
  81.   //由Socket对象得到输出流,并构造PrintWriter对象    
  82.   os   =   new   PrintWriter(s.getOutputStream());    
  83.   }    
  84.   catch   (IOException   ex)   {    
  85.   System.out.println("Error   on   get   Buffere");    
  86.   }    
  87.      
  88.   String   temp   =   "";    
  89.   try   {    
  90.   temp   =   is.readLine();    
  91.   while   (temp   !=   null)   {    
  92.   msg   +=   temp;    
  93.   if   (temp.length()   >   4   &&    
  94.   temp.substring(temp.length()   -   4).equals("/End"))   {    
  95.   temp   =   is.readLine();   //虚读    
  96.   temp   =   null;    
  97.   break;    
  98.   }    
  99.   msg   +=   "\r\n";    
100.   temp   =   is.readLine();    
101.   }    
102.   getMsg();    
103.   //立刻回发消息    
104.   msg   =   "Begin/"   +   msg   +   "/End";    
105.   os.write("HTTP/1.1   200   OK\r\n");    
106.   os.write("Content-Type:   text;   charset=utf\r\n");    
107.   os.write(   ("Content-Length:   "   +   msg.length()   +   "\r\n"));    
108.   os.write("\r\n");    
109.   os.write(msg);    
110.   os.flush();    
111.   msg   =   "";    
112.   }    
113.   catch   (IOException   ex1)   {    
114.   System.out.println("Error   on   read   or   write   Buffered");    
115.   ex1.printStackTrace();    
116.   }    
117.   try   {    
118.   sleep(100);    
119.   }    
120.   catch   (InterruptedException   ex2)   {    
121.   System.out.println("Error   on   HttpSocket   sleep");    
122.   }    
123.   }    
124.      
125.   //去掉协议头,取出纯消息    
126.   private   void   getMsg()   {    
127.   int   begin   =   msg.indexOf("Begin/");    
128.   int   end   =   msg.indexOf("/End");    
129.   if   (begin   >=   0   &&   end   >   0   &&   msg.length()>"Begin/".length())   {    
130.   msg   =   msg.substring(begin   +   "Begin/".length(),   end);    
131.   System.out.println(msg);    
132.   }    
133.   else   {    
134.   msg   =   "";    
135.   }    
136.   }    
137.   }    

服务器示例代码:(共三个类)  
  //HttpServer.java  
  package   testnetserver;  
   
  public   class   HttpServer{  
  public   HttpServer()   {  
  }  
  public   static   void   main(String[]   aregs){  
  HttpServerSocket   hss=new   HttpServerSocket();  
  hss.start();  
  }  
  }  
   
   
   
   
   
   
  //HttpServerSocket.java  
  package   testnetserver;  
   
  import   java.net.ServerSocket;  
  import   java.io.*;  
   
  public   class   HttpServerSocket   extends   Thread{  
  ServerSocket   ss=null;  
  private   static   final   int   port=2222;  
  public   HttpServerSocket()   {  
  }  
  public   void   run(){  
  try   {  
  ss   =   new   ServerSocket(port);  
  }  
  catch   (IOException   ex)   {  
  System.out.println("ServerSocket   can   not   listen");  
  System.out.println("Error   on   ServerSocket   bind   port");  
  ex.printStackTrace();  
  ss=null;  
  return;  
  }  
  //循环监听  
  while(true){  
  HttpSocket   hs=null;  
  try   {  
  hs=new   HttpSocket();  
  hs.s=ss.accept();  
  System.out.println("have   a   client   connect");  
  hs.start();  
  }  
  catch   (IOException   ex1)   {  
  System.out.println("Error   on   accept");  
  }  
  }  
  }  
  }  
   
   
   
   
   
   
  //HttpSocket.java  
  package   testnetserver;  
   
  import   java.net.Socket;  
  import   java.io.*;  
   
  public   class   HttpSocket  
  extends   Thread   {  
  public   Socket   s   =   null;  
  String   msg   =   "";  
  public   HttpSocket()   {  
  }  
   
  public   void   run()   {  
  BufferedReader   is   =   null;  
  PrintWriter   os   =   null;  
  try   {  
  //由Socket对象得到输入流,并构造相应的BufferedReader对象  
  is   =   new   BufferedReader(new   InputStreamReader(s.getInputStream()));  
  //由Socket对象得到输出流,并构造PrintWriter对象  
  os   =   new   PrintWriter(s.getOutputStream());  
  }  
  catch   (IOException   ex)   {  
  System.out.println("Error   on   get   Buffere");  
  }  
   
  String   temp   =   "";  
  try   {  
  temp   =   is.readLine();  
  while   (temp   !=   null)   {  
  msg   +=   temp;  
  if   (temp.length()   >   4   &&  
  temp.substring(temp.length()   -   4).equals("/End"))   {  
  temp   =   is.readLine();   //虚读  
  temp   =   null;  
  break;  
  }  
  msg   +=   "\r\n";  
  temp   =   is.readLine();  
  }  
  getMsg();  
  //立刻回发消息  
  msg   =   "Begin/"   +   msg   +   "/End";  
  os.write("HTTP/1.1   200   OK\r\n");  
  os.write("Content-Type:   text;   charset=utf\r\n");  
  os.write(   ("Content-Length:   "   +   msg.length()   +   "\r\n"));  
  os.write("\r\n");  
  os.write(msg);  
  os.flush();  
  msg   =   "";  
  }  
  catch   (IOException   ex1)   {  
  System.out.println("Error   on   read   or   write   Buffered");  
  ex1.printStackTrace();  
  }  
  try   {  
  sleep(100);  
  }  
  catch   (InterruptedException   ex2)   {  
  System.out.println("Error   on   HttpSocket   sleep");  
  }  
  }  
   
  //去掉协议头,取出纯消息  
  private   void   getMsg()   {  
  int   begin   =   msg.indexOf("Begin/");  
  int   end   =   msg.indexOf("/End");  
  if   (begin   >=   0   &&   end   >   0   &&   msg.length()>"Begin/".length())   {  
  msg   =   msg.substring(begin   +   "Begin/".length(),   end);  
  System.out.println(msg);  
  }  
  else   {  
  msg   =   "";  
  }  
  }  
  }  




Java代码

   1. 客户端示例代码(主要部份):    
   2.   public   void   run()   {    
   3.   HttpConnection   conn   =   null;    
   4.   DataInputStream   dis   =   null;    
   5.   DataOutputStream   dos   =   null;    
   6.   int   begin   =   0,   end   =   0;    
   7.   byte   temp[]   =   new   byte[10000];    
   8.   int   len   =   0;    
   9.   try   {    
  10.   conn   =   (HttpConnection)   Connector.open("http://"   +   IP   +   ":"   +    
  11.   port);    
  12.                           //写输出流(向服务器发送信息)    
  13.   dos   =   conn.openDataOutputStream();    
  14.   msg   =   "Begin/"   +   msg+"/End";    
  15.   //dos.writeUTF(msg);    
  16.   dos.write(msg.getBytes());    
  17.   dos.flush();    
  18.   dos.close();    
  19.   if   (!isTestConnectTime)   {    
  20.   dataLenght   =   msg.length();    
  21.   }    
  22.   backTime   =   0;    
  23.   //读输入流(读服务器消息)    
  24.   dis   =   conn.openDataInputStream();    
  25.   len   =   dis.read(temp);    
  26.   if   (len   >   0)   {    
  27.   receiveMsg   =   "";    
  28.   for   (int   i   =   0;   i   <   len;   i++)   {    
  29.   receiveMsg   +=   (char)   temp[i];    
  30.   }    
  31.   }    
  32.      
  33.   if   (receiveMsg.length()   >   0)   {    
  34.   begin   =   receiveMsg.indexOf("Begin/");    
  35.   end   =   receiveMsg.indexOf("/End");    
  36.   if   (begin   >=   0   &&   end   >   0)   {    
  37.   receiveMsg   =   receiveMsg.substring(begin   +    
  38.   "Begin/".length(),   end);    
  39.   if   (receiveMsg   !=   null   &&   receiveMsg.trim()   !=   ""   &&    
  40.   receiveMsg.length()   >   0)   {    
  41.   System.out.println(receiveMsg);    
  42.   testCount++;    
  43.   if   (!isTestConnectTime)   {    
  44.   allDataLenght   +=   dataLenght;    
  45.   }    
  46.   }    
  47.   }    
  48.   }    
  49.   //dos.close();    
  50.   dis.close();    
  51.   conn.close();    
  52.   }    
  53.   catch   (Exception   ex1)   {    
  54.   System.out.println("Error   on   send   message");    
  55.   ex1.printStackTrace();    
  56.   }    
  57.   } 
分享到:
评论
3 楼 孤独舞者 2013-09-22  
xkb281 写道
不错啊,SOCKET这部分好多地方含糊,这篇文章让我理解许多,

引用别人的
2 楼 xkb281 2011-11-13  
不错啊,SOCKET这部分好多地方含糊,这篇文章让我理解许多,
1 楼 george_space 2011-07-29  
顶,好文章。

相关推荐

Global site tag (gtag.js) - Google Analytics