JAVA SOCKET的2种实现

    技术2022-05-20  48

    <!-- /* Font Definitions */ @font-face {font-family:Wingdings; panose-1:5 0 0 0 0 0 0 0 0 0; mso-font-charset:2; mso-generic-font-family:auto; mso-font-pitch:variable; mso-font-signature:0 268435456 0 0 -2147483648 0;} @font-face {font-family:宋体; panose-1:2 1 6 0 3 1 1 1 1 1; mso-font-alt:SimSun; mso-font-charset:134; mso-generic-font-family:auto; mso-font-pitch:variable; mso-font-signature:3 135135232 16 0 262145 0;} @font-face {font-family:"/@宋体"; panose-1:2 1 6 0 3 1 1 1 1 1; mso-font-charset:134; mso-generic-font-family:auto; mso-font-pitch:variable; mso-font-signature:3 135135232 16 0 262145 0;} /* Style Definitions */ p.MsoNormal, li.MsoNormal, div.MsoNormal {mso-style-parent:""; margin-top:0cm; margin-right:0cm; margin-bottom:6.0pt; margin-left:0cm; mso-pagination:none; mso-layout-grid-align:none; text-autospace:none; font-size:10.5pt; mso-bidi-font-size:10.0pt; font-family:"Times New Roman"; mso-fareast-font-family:宋体;} p.MsoHeader, li.MsoHeader, div.MsoHeader {margin-top:0cm; margin-right:0cm; margin-bottom:6.0pt; margin-left:0cm; text-align:center; mso-pagination:none; tab-stops:center 207.65pt right 415.3pt; layout-grid-mode:char; mso-layout-grid-align:none; text-autospace:none; border:none; mso-border-bottom-alt:solid windowtext .75pt; padding:0cm; mso-padding-alt:0cm 0cm 1.0pt 0cm; font-size:9.0pt; font-family:"Times New Roman"; mso-fareast-font-family:宋体;} p.MsoFooter, li.MsoFooter, div.MsoFooter {margin-top:0cm; margin-right:0cm; margin-bottom:6.0pt; margin-left:0cm; mso-pagination:none; tab-stops:center 207.65pt right 415.3pt; layout-grid-mode:char; mso-layout-grid-align:none; text-autospace:none; font-size:9.0pt; font-family:"Times New Roman"; mso-fareast-font-family:宋体;} /* Page Definitions */ @page {mso-page-border-surround-header:no; mso-page-border-surround-footer:no;} @page Section1 {size:595.3pt 841.9pt; margin:72.0pt 90.0pt 72.0pt 90.0pt; mso-header-margin:42.55pt; mso-footer-margin:49.6pt; mso-paper-source:0; layout-grid:15.6pt;} div.Section1 {page:Section1;} /* List Definitions */ @list l0 {mso-list-id:166480649; mso-list-type:hybrid; mso-list-template-ids:775840906 942051372 67698689 67698703 658045874 67698713 67698715 67698703 67698713 67698715;} @list l0:level1 {mso-level-number-format:chinese-counting-thousand; mso-level-text:%1、; mso-level-tab-stop:21.0pt; mso-level-number-position:left; margin-left:21.0pt; text-indent:-21.0pt; mso-ansi-language:EN-US;} @list l0:level2 {mso-level-number-format:bullet; mso-level-text:; mso-level-tab-stop:42.0pt; mso-level-number-position:left; margin-left:42.0pt; text-indent:-21.0pt; font-family:Wingdings; mso-ansi-language:EN-US;} @list l0:level3 {mso-level-tab-stop:108.0pt; mso-level-number-position:left; text-indent:-18.0pt;} @list l0:level4 {mso-level-tab-stop:81.0pt; mso-level-number-position:left; margin-left:81.0pt; text-indent:-18.0pt; mso-ansi-language:EN-US;} @list l0:level5 {mso-level-tab-stop:180.0pt; mso-level-number-position:left; text-indent:-18.0pt;} @list l0:level6 {mso-level-tab-stop:216.0pt; mso-level-number-position:left; text-indent:-18.0pt;} @list l0:level7 {mso-level-tab-stop:252.0pt; mso-level-number-position:left; text-indent:-18.0pt;} @list l0:level8 {mso-level-tab-stop:288.0pt; mso-level-number-position:left; text-indent:-18.0pt;} @list l0:level9 {mso-level-tab-stop:324.0pt; mso-level-number-position:left; text-indent:-18.0pt;} @list l1 {mso-list-id:1037196937; mso-list-type:hybrid; mso-list-template-ids:-645251058 658045874 67698713 67698715 67698703 67698713 67698715 67698703 67698713 67698715;} @list l1:level1 {mso-level-tab-stop:81.0pt; mso-level-number-position:left; margin-left:81.0pt; text-indent:-18.0pt; mso-ansi-language:EN-US;} ol {margin-bottom:0cm;} ul {margin-bottom:0cm;} -->

    JAVA SOCKET 2 种实现

    一、      TCP 实现

    Java Socket 编程 TCP 实现,比较容易懂。

      服务端代码

    import java.io.IOException;

       import java.net.InetAddress;

       import java.net.Socket;

       public class ServerSocket {

       public static void main(String[] args) {

       beginSocket();

       }

       public static void beginSocket(){

       try {

       java.net.ServerSocket serverSocket=new java.net.ServerSocket(3456);

       InetAddress inta=serverSocket.getInetAddress().getLocalHost();

       System.out.println(inta.getHostAddress());

       while(true){

       Socket socket=serverSocket.accept();

       new HelloMessage(socket);

       }

       } catch (IOException e) {

       e.printStackTrace();

       }

       }

       }

     

        // 为了提高并发时的处理效率,对于每个请求,系统都新建一个线程处理。

       Java 代码

       import java.io.BufferedReader;

       import java.io.InputStreamReader;

       import java.io.PrintWriter;

       import java.net.Socket;

       public class HelloMessage extends Thread {

       private Socket socket_ = null;

       public HelloMessage(Socket socket) {

       this.socket_ = socket;

       this.start();

       }

       public void run() {

       try {

       BufferedReader bReader = new BufferedReader(new InputStreamReader(

       this.socket_.getInputStream()));

       PrintWriter pWriter = new PrintWriter(this.socket_

       .getOutputStream());

       String requestStr = bReader.readLine();

       if (requestStr != null && !"".equals(requestStr)) {

       if (requestStr.equals("java")) {

       pWriter.println("your write is java");

       }

       if (requestStr.equals(".net")) {

       pWriter.println("your write is .net");

       }

       if (requestStr.equals("php")) {

       pWriter.println("your write is php");

       }

     

       if (requestStr.equals("end")) {

       pWriter.println("your write is end");

       }else{

       pWriter.println("your write is other");

       }

       }else{

       pWriter.println("your write is null");

       }

       pWriter.flush();

       pWriter.close();

       bReader.close();

       this.socket_.close();

       } catch (Exception e) {

       e.printStackTrace();

       }

    }

    }

    客户端代码

    import java.io.BufferedReader;

       import java.io.IOException;

       import java.io.InputStreamReader;

       import java.io.PrintWriter;

       import java.net.Socket;

       import java.net.UnknownHostException;

       public class ClientSocket {

       public static void main(String[] args) {

    clientRequest();

       }

       private static void clientRequest() {

     

       try {

       while (true) {

       Socket clientSocket = new Socket("172.168.4.105", 3456);

       BufferedReader bReader = new BufferedReader(new InputStreamReader(

       System.in));

       System.out.println("please input java or .net or php or end");

       String strLine = bReader.readLine();

       if (strLine != null && !"".equals(strLine)) {

       PrintWriter pWriter = new PrintWriter(clientSocket

       .getOutputStream(), true);

       pWriter.println(strLine);

       BufferedReader br = new BufferedReader(

       new InputStreamReader(clientSocket.getInputStream()));

       String strResult = br.readLine();

       System.out.println(strResult);

       pWriter.flush();

       pWriter.close();

       clientSocket.close();

       }

       }

       } catch (UnknownHostException e) {

       e.printStackTrace();

       } catch (IOException e) {

       e.printStackTrace();

       }

       }

       }

      这样一个简单的 TCP Socket 编程的原型就成了。简单介绍下:

      几个比较重要的API

     

       .Accept 方法用于产生 " 阻塞 " ,直到接受到一个连接,并且返回一个客户端的 Socket 对象实例。

       .getInputStream 方法获得网络连接输入,同时返回一个 IutputStream 对象实例,。

       .getOutputStream 方法连接的另一端将得到输入,同时返回一个 OutputStream 对象实例。

     

    二、      UDP 实现

    import java.io.IOException;

    import java.net.DatagramPacket;

    import java.net.DatagramSocket;

       import java.net.InetAddress;

       import java.net.SocketException;

       public class UDPReceive {

       public static void main(String[] args) {

       Integer port = 2345;

       byte[] buffer = new byte[2048];

       try {

       DatagramSocket datagramSocket = new DatagramSocket(port);

       DatagramPacket datagramPacket = new DatagramPacket(buffer,buffer.length);

       try {

       for (;;) {

       System.out.println("begin receive data....");

       datagramSocket.receive(datagramPacket);

    System.out.println(datagramPacket.getAddress().getAddress().toString()+"======="

    +new String(datagramPacket.getData()));

       datagramPacket.setLength(datagramPacket.getData().toString().length());

       }

       } catch (IOException e) {

       e.printStackTrace();

       }

       } catch (SocketException e) {

       e.printStackTrace();

       }

       }

       }

     

      客户端代码

       import java.io.IOException;

       import java.net.DatagramPacket;

       import java.net.DatagramSocket;

       import java.net.InetAddress;

       import java.net.SocketException;

       import java.net.UnknownHostException;

       public class UDPSend {

       public static void main(String[] args) {

       try {

       for (;;) {

       DatagramSocket sendSocket = new DatagramSocket();

       DatagramPacket dataPack = new DatagramPacket(

       "hello ,welcome to study java..".getBytes(),

       "hello ,welcome to study java..".length(), InetAddress

       .getByName("127.0.0.1"), new Integer(2345));

       try {

       sendSocket.send(dataPack);

       sendSocket.close();

       } catch (IOException e) {

       e.printStackTrace();

       }

       }

       } catch (SocketException e) {

       e.printStackTrace();

       } catch (UnknownHostException e) {

       e.printStackTrace();

       }

       }

       }

    三、      比较

    UDP:

    1.       每个数据报文中都给出了完整的地址信息,因此无需建立接收方和发送方的连接。

    2.       UDP 传输有大小限制,每个传输的数据报文必须在 64KB 之内。

    3.       UDP 是一个不可靠协议,数据报文并不一定按照顺序到达接收方。

    TCP:

    1.       需要建立连接,所以建立连接需要时间。

    2.       建立连接之后,双发就可以按照统一的格式传输大的数据。

    3.       TCP 是一个可靠协议,接收方可以完全正确的获取发送方所发送的所有数据。

    四、      应用

    UDP:

         UDP 操作简单,很少需要监护,通常用于局域网高可靠性的分散系统,例如视频会议,并不需要视频数据的绝对正确,只需要连贯就可以了。这时使用 UDP 更合理一些。

    TCP:

          TCP 在网络通信上很出色,例如 Telnet FTP 都需要不定长的数据被完整的传输,但是可靠传输是要付出代价的,它会占用计算机处理时间和网络带宽。因此, tcp 的传输效率并不比 UDP 高。


    最新回复(0)