Comparison of. Net and Java socket mechanisms

Source: Internet
Author: User

A socket is a high-level interface based on TCP and UDP protocols. It defines the format for sending and receiving data. The Socket used in Java's TCP Service is a stream mechanism. For programmers, to process a socket, they only need to obtain the stream from the Socket, then, you can send and receive data like a local stream.

For example:

DataOutputStream outToClient = new DataOutputStream (socket. getOutputStream ());

BufferedReader inFromClient = new BufferedReader (new InputStreamReader (socket. getInputStream ()));

String requestMessageLine = inFromClient. readLine ();

OutToClient. writeBytes (requestMessageLine );
 
The Socket mechanism of. Net provides two implementations: one is to directly use the Socket class, and the other is to use the TcpClient and UdpClient classes that encapsulate the Socket again .. Net provides a unified transmission and receiving mechanism: NetworkStream.

Both TcpClient and Socket use NetworkStream to transmit data at the underlying layer. Both of them can generate a NetworkStream. For example:

TcpClient client = server. AcceptTcpClient (); NetworkStream = client. GetStream ();

The biggest difference between. Net socket and Java socket in sending and receiving data is that Java socket can operate like a normal stream .. Net socket has a variety of implementation methods, you can directly use Socket. send () to send, you can also use NetwordStream to send, you can also use TcpClient to send. However, each implementation performs operations on the buffer zone when sending and receiving data. For example:

Byte [] datasize = new byte [4]; networkStream. Write (datasize, 0, 4); socket. Send (datasize, 0, datasize. Length, 0 );

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.