欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

基于Java回顾之网络通信的应用分析

程序员文章站 2024-03-31 10:09:16
tcp连接 tcp的基础是socket,在tcp连接中,我们会使用serversocket和socket,当客户端和服务器建立连接以后,剩下的基本就是对i/o的控制了。...

tcp连接

tcp的基础是socket,在tcp连接中,我们会使用serversocket和socket,当客户端和服务器建立连接以后,剩下的基本就是对i/o的控制了。

我们先来看一个简单的tcp通信,它分为客户端和服务器端。

客户端代码如下:

复制代码 代码如下:

简单的tcp客户端
 import java.net.*;
 import java.io.*;
 public class simpletcpclient {

     public static void main(string[] args) throws ioexception
     {
         socket socket = null;
         bufferedreader br = null;
         printwriter pw = null;
         bufferedreader brtemp = null;
         try
         {
             socket = new socket(inetaddress.getlocalhost(), 5678);
             br = new bufferedreader(new inputstreamreader(socket.getinputstream()));
             pw = new printwriter(socket.getoutputstream());
             brtemp = new bufferedreader(new inputstreamreader(system.in));
             while(true)
             {
                 string line = brtemp.readline();
                 pw.println(line);
                 pw.flush();
                 if (line.equals("end")) break;
                 system.out.println(br.readline());
             }
         }
         catch(exception ex)
         {
             system.err.println(ex.getmessage());
         }
         finally
         {
             if (socket != null) socket.close();
             if (br != null) br.close();
             if (brtemp != null) brtemp.close();
             if (pw != null) pw.close();
         }
     }
 }

服务器端代码如下:
复制代码 代码如下:

简单版本tcp服务器端
 import java.net.*;
 import java.io.*;
 public class simpletcpserver {

     public static void main(string[] args) throws ioexception
     {
         serversocket server = null;
         socket client = null;
         bufferedreader br = null;
         printwriter pw = null;
         try
         {
             server = new serversocket(5678);
             client = server.accept();
             br = new bufferedreader(new inputstreamreader(client.getinputstream()));
             pw = new printwriter(client.getoutputstream());
             while(true)
             {
                 string line = br.readline();
                 pw.println("response:" + line);
                 pw.flush();
                 if (line.equals("end")) break;
             }
         }
         catch(exception ex)
         {
             system.err.println(ex.getmessage());
         }
         finally
         {
             if (server != null) server.close();
             if (client != null) client.close();
             if (br != null) br.close();
             if (pw != null) pw.close();
         }
     }
 }

这里的服务器的功能非常简单,它接收客户端发来的消息,然后将消息“原封不动”的返回给客户端。当客户端发送“end”时,通信结束。

上面的代码基本上勾勒了tcp通信过程中,客户端和服务器端的主要框架,我们可以发现,上述的代码中,服务器端在任何时刻,都只能处理来自客户端的一个请求,它是串行处理的,不能并行,这和我们印象里的服务器处理方式不太相同,我们可以为服务器添加多线程,当一个客户端的请求进入后,我们就创建一个线程,来处理对应的请求。

改善后的服务器端代码如下:

复制代码 代码如下:

多线程版本的tcp服务器端
 import java.net.*;
 import java.io.*;
 public class smarttcpserver {
     public static void main(string[] args) throws ioexception
     {
         serversocket server = new serversocket(5678);
         while(true)
         {
             socket client = server.accept();
             thread thread = new serverthread(client);
             thread.start();
         }
     }
 }

 class serverthread extends thread
 {
     private socket socket = null;

     public serverthread(socket socket)
     {
         this.socket = socket;
     }

     public void run() {
         bufferedreader br = null;
         printwriter pw = null;
         try
         {
             br = new bufferedreader(new inputstreamreader(socket.getinputstream()));
             pw = new printwriter(socket.getoutputstream());
             while(true)
             {
                 string line = br.readline();
                 pw.println("response:" + line);
                 pw.flush();
                 if (line.equals("end")) break;
             }
         }
         catch(exception ex)
         {
             system.err.println(ex.getmessage());
         }
         finally
         {
             if (socket != null)
                 try {
                     socket.close();
                 } catch (ioexception e1) {
                     e1.printstacktrace();
                 }
             if (br != null)
                 try {
                     br.close();
                 } catch (ioexception e) {
                     e.printstacktrace();
                 }
             if (pw != null) pw.close();
         }
     }
 }

修改后的服务器端,就可以同时处理来自客户端的多个请求了。

在编程的过程中,我们会有“资源”的概念,例如数据库连接就是一个典型的资源,为了提升性能,我们通常不会直接销毁数据库连接,而是使用数据库连接池的方式来对多个数据库连接进行管理,已实现重用的目的。对于socket连接来说,它也是一种资源,当我们的程序需要大量的socket连接时,如果每个连接都需要重新建立,那么将会是一件非常没有效率的做法。

和数据库连接池类似,我们也可以设计tcp连接池,这里的思路是我们用一个数组来维持多个socket连接,另外一个状态数组来描述每个socket连接是否正在使用,当程序需要socket连接时,我们遍历状态数组,取出第一个没被使用的socket连接,如果所有连接都在使用,抛出异常。这是一种很直观简单的“调度策略”,在很多开源或者商业的框架中(apache/tomcat),都会有类似的“资源池”。

tcp连接池的代码如下:

复制代码 代码如下:

一个简单的tcp连接池
 import java.net.*;
 import java.io.*;
 public class tcpconnectionpool {

     private inetaddress address = null;
     private int port;
     private socket[] arrsockets = null;
     private boolean[] arrstatus = null;
     private int count;

     public tcpconnectionpool(inetaddress address, int port, int count)
     {
         this.address = address;
         this.port = port;
         this .count = count;
         arrsockets = new socket[count];
         arrstatus = new boolean[count];

         init();
     }

     private void init()
     {
         try
         {
             for (int i = 0; i < count; i++)
             {
                 arrsockets[i] = new socket(address.gethostaddress(), port);
                 arrstatus[i] = false;
             }
         }
         catch(exception ex)
         {
             system.err.println(ex.getmessage());
         }
     }

     public socket getconnection()
     {
         if (arrsockets == null) init();
         int i = 0;
         for(i = 0; i < count; i++)
         {
             if (arrstatus[i] == false)
             {
                 arrstatus[i] = true;
                 break;
             }
         }
         if (i == count) throw new runtimeexception("have no connection availiable for now.");

         return arrsockets[i];
     }

     public void releaseconnection(socket socket)
     {
         if (arrsockets == null) init();
         for (int i = 0; i < count; i++)
         {
             if (arrsockets[i] == socket)
             {
                 arrstatus[i] = false;
                 break;
             }
         }
     }

     public void rebuild()
     {
         init();
     }

     public void destory()
     {
         if (arrsockets == null) return;

         for(int i = 0; i < count; i++)
         {
             try
             {
                 arrsockets[i].close();
             }
             catch(exception ex)
             {
                 system.err.println(ex.getmessage());
                 continue;
             }
         }
     }
 }

udp连接

udp是一种和tcp不同的连接方式,它通常应用在对实时性要求很高,对准确定要求不高的场合,例如在线视频。udp会有“丢包”的情况发生,在tcp中,如果server没有启动,client发消息时,会报出异常,但对udp来说,不会产生任何异常。

udp通信使用的两个类时datagramsocket和datagrampacket,后者存放了通信的内容。

下面是一个简单的udp通信例子,同tcp一样,也分为client和server两部分,client端代码如下:

复制代码 代码如下:

udp通信客户端
 import java.net.*;
 import java.io.*;
 public class udpclient {

     public static void main(string[] args)
     {
         try
         {
             inetaddress host = inetaddress.getlocalhost();
             int port = 5678;
             bufferedreader br = new bufferedreader(new inputstreamreader(system.in));
             while(true)
             {
                 string line = br.readline();
                 byte[] message = line.getbytes();
                 datagrampacket packet = new datagrampacket(message, message.length, host, port);
                 datagramsocket socket = new datagramsocket();
                 socket.send(packet);
                 socket.close();
                 if (line.equals("end")) break;
             }
             br.close();
         }
         catch(exception ex)
         {
             system.err.println(ex.getmessage());
         }
     }
 }

server端代码如下:
复制代码 代码如下:

udp通信服务器端
 import java.net.*;
 import java.io.*;
 public class udpserver {

     public static void main(string[] args)
     {
         try
         {
             int port = 5678;
             datagramsocket dssocket = new datagramsocket(port);
             byte[] buffer = new byte[1024];
             datagrampacket packet = new datagrampacket(buffer, buffer.length);
             while(true)
             {
                 dssocket.receive(packet);
                 string message = new string(buffer, 0, packet.getlength());
                 system.out.println(packet.getaddress().gethostname() + ":" + message);
                 if (message.equals("end")) break;
                 packet.setlength(buffer.length);
             }
             dssocket.close();
         }
         catch(exception ex)
         {
             system.err.println(ex.getmessage());
         }
     }
 }

这里,我们也假设和tcp一样,当client发出“end”消息时,认为通信结束,但其实这样的设计不是必要的,client端可以随时断开,并不需要关心server端状态。
多播(multicast)

多播采用和udp类似的方式,它会使用d类ip地址和标准的udp端口号,d类ip地址是指224.0.0.0到239.255.255.255之间的地址,不包括224.0.0.0。

多播会使用到的类是multicastsocket,它有两个方法需要关注:joingroup和leavegroup。

下面是一个多播的例子,client端代码如下:

复制代码 代码如下:

多播通信客户端
 import java.net.*;
 import java.io.*;
 public class multicastclient {

     public static void main(string[] args)
     {
         bufferedreader br = new bufferedreader(new inputstreamreader(system.in));
         try
         {
             inetaddress address = inetaddress.getbyname("230.0.0.1");
             int port = 5678;
             while(true)
             {
                 string line = br.readline();
                 byte[] message = line.getbytes();
                 datagrampacket packet = new datagrampacket(message, message.length, address, port);
                 multicastsocket multicastsocket = new multicastsocket();
                 multicastsocket.send(packet);
                 if (line.equals("end")) break;
             }
             br.close();
         }
         catch(exception ex)
         {
             system.err.println(ex.getmessage());
         }
     }
 }

服务器端代码如下:
复制代码 代码如下:

多播通信服务器端
 import java.net.*;
 import java.io.*;
 public class multicastserver {

     public static void main(string[] args)
     {
         int port = 5678;
         try
         {
             multicastsocket multicastsocket = new multicastsocket(port);
             inetaddress address = inetaddress.getbyname("230.0.0.1");
             multicastsocket.joingroup(address);
             byte[] buffer = new byte[1024];
             datagrampacket packet = new datagrampacket(buffer, buffer.length);
             while(true)
             {
                 multicastsocket.receive(packet);
                 string message = new string(buffer, packet.getlength());
                 system.out.println(packet.getaddress().gethostname() + ":" + message);
                 if (message.equals("end")) break;
                 packet.setlength(buffer.length);
             }
             multicastsocket.close();
         }
         catch(exception ex)
         {
             system.err.println(ex.getmessage());
         }
     }
 }

nio(new io)

nio是jdk1.4引入的一套新的io api,它在缓冲区管理、网络通信、文件存取以及字符集操作方面有了新的设计。对于网络通信来说,nio使用了缓冲区和通道的概念。

下面是一个nio的例子,和我们上面提到的代码风格有很大的不同。

复制代码 代码如下:

nio例子
 import java.io.*;
 import java.nio.*;
 import java.nio.channels.*;
 import java.nio.charset.*;
 import java.net.*;
 public class newiosample {

     public static void main(string[] args)
     {
         string host="127.0.0.1";
         int port = 5678;
         socketchannel channel = null;
         try
         {
             inetsocketaddress address = new inetsocketaddress(host,port);
             charset charset = charset.forname("utf-8");
             charsetdecoder decoder = charset.newdecoder();
             charsetencoder encoder = charset.newencoder();

             bytebuffer buffer = bytebuffer.allocate(1024);
             charbuffer charbuffer = charbuffer.allocate(1024);

             channel = socketchannel.open();
             channel.connect(address);

             string request = "get / \r\n\r\n";
             channel.write(encoder.encode(charbuffer.wrap(request)));

             while((channel.read(buffer)) != -1)
             {
                 buffer.flip();
                 decoder.decode(buffer, charbuffer, false);
                 charbuffer.flip();
                 system.out.println(charbuffer);
                 buffer.clear();
                 charbuffer.clear();
             }
         }
         catch(exception ex)
         {
             system.err.println(ex.getmessage());
         }
         finally
         {
             if (channel != null)
                 try {
                     channel.close();
                 } catch (ioexception e) {
                     // todo auto-generated catch block
                     e.printstacktrace();
                 }
         }
     }
 }

上述代码会试图访问一个本地的网址,然后将其内容打印出来。