Java Fundamentals Eight (network in java,c++)

Source: Internet
Author: User
Tags epoll htons

The basics are written here, and the basics of C + + and Java are done, and for more in-depth use, you'll need to look for a unique class library for each language.

Talking about the network, it is inevitable to talk about the basic use of TCP/IP. This article only for two languages of the network implementation to do a brief introduction, follow-up learning if there is a detailed description, will be gradually added to this article.

1. C + + network knowledge

Simple TCP/IP:

Server side:

#include <winsock2. h> #include <stdio.h> #pragma comment (lib, "Ws2_32.lib") void Main () {//create socket word myversionrequest; Wsadata Wsadata; Myversionrequest=makeword (a); int err; Err=wsastartup (Myversionrequest,&wsadata);  if (!err) {printf ("opened socket \ n");}  else {//further bind socket printf ("The nested word is not open!"); Return } socket Sersocket=socket (af_inet,sock_stream,0);//Create an identifiable socket//required to bind the parameters sockaddr_in addr; Addr.sin_family=af_inet; Addr.sin_addr. S_un. S_addr=htonl (Inaddr_any);//IP address addr.sin_port=htons (6000);//Bind Port bind (Sersocket, (sockaddr*) &addr,sizeof ( SOCKADDR));//Bind complete listen (sersocket,5);//The second parameter represents the maximum number of connections that can be received/////////////////////////////////////////////////// Start the monitoring////////////////////////////////////////////////////////////////////////// Sockaddr_in Clientsocket; int len=sizeof (SOCKADDR); while (1) {SOCKET serconn=accept (Sersocket, (sockaddr*) &clientsocket,&len);//If this is not accept but conection.    Will constantly listen to Char sendbuf[100]; sprintf (SendBuf, "Welcome %s to Bejing ", Inet_ntoa (CLIENTSOCKET.SIN_ADDR)),//find the corresponding IP and print the line to there send (Serconn,sendbuf,strlen (SENDBUF) +1,0);  Char receivebuf[100];//receive recv (Serconn,receivebuf,strlen (RECEIVEBUF) +1,0);  printf ("%s\n", receivebuf); Closesocket (serconn);//close WSACleanup ();//Release resource Operation}}
Client side:

 #include <winsock2. h> #include <stdio.h> #pragma comment (lib, "Ws2_32.lib") void Main () {int err; WORD versionrequired; Wsadata Wsadata; Versionrequired=makeword (a); Err=wsastartup (versionrequired,&wsadata);//The version information of the Protocol Library if (!err) {printf ("The client nested word has been opened!\n");} else {printf ("  The client's nested word open failed!\n "); return;//End} SOCKET clientsocket=socket (af_inet,sock_stream,0); Sockaddr_in clientsock_in; Clientsock_in.sin_addr. S_un. S_ADDR=INET_ADDR ("127.0.0.1"); Clientsock_in.sin_family=af_inet; Clientsock_in.sin_port=htons (6000); Bind (Clientsocket, (sockaddr*) &clientsock_in,strlen (sockaddr));//Note The third parameter//listen (clientsocket,5); Connect (Clientsocket, (sockaddr*) &clientsock_in,sizeof (sockaddr));//Start connecting char receivebuf[100]; Recv (clientsocket,receivebuf,101,0); printf ("%s\n", receivebuf); Send (Clientsocket, "Hello,this is the client", strlen ("Hello,this is Client") +1,0); Closesocket (Clientsocket); WSACleanup ();} 
The above example can only be used as a simple example of familiarity with TCP/UDP, and in practical development we often need to use open source Cullemo to complete development. Recommend a more comprehensive introduction to the open source C + + network library article:

http://blog.csdn.net/langeldep/article/details/6976120

Summary:

In the open-source C + + network library, commonly used in a few, the industry's highest visibility, it should be ace, but a heavyweight big, lightweight with libevent, Libev, and boost ASIO.

The boost ASIO is an asynchronous IO library that encapsulates common operations on sockets and simplifies the development of socket-based programs. Support cross-platform.

Libevent is a C-language network library, the official main support is the class Linux operating system, the latest version added to the Windows IOCP support. Since IOCP is asynchronous IO, with the poll model under Linux, the Epoll model, and the kqueue of FreeBSD, these synchronization models are completely inconsistent in usage, so the use of the method is not the same as the reactor and proactor patterns in Ace, Use needs to change the way of thinking. If there is no specific requirement for performance, then using the Select model in libevent for cross-platform operations, the Select model can span systems such as Windows, Linux, Unix,solaris, and so on.

Libev is a C language, only support the Linux system library, I previously studied the time only encapsulated the Epoll model, do not know whether the new version has been improved. The use method is similar to libevent, but very concise, the code amount is the least one library, also thousands of lines of code. Obviously this kind of code cross-platform certainly is unable to support, if you only need to run under Linux, then use this library is also possible.


2. Java Network Knowledge
Network programming is nothing more than server-side monitoring and client connection, so its foundation is very simple, it may be difficult on the asynchronous network communication, as well as some of the use of the framework, here for the moment the simple use of TCP/IP is posted out, and introduce some of the use of the framework.

A simple example of TCP/IP (Source: http://blog.csdn.net/wintys/article/details/3525619):

Server side:

/** *tcpserver * @author winty [email protected] * @version 2008-12-15 */import java.io.*;import java.net.*;class tcpserver {public    static void Main (string[] args) throws ioexception{        ServerSocket listen = new ServerSocket (5050);                Socket Server  = Listen.accept ();        InputStream in = Server.getinputstream ();        OutputStream out = Server.getoutputstream ();        char C = (char) in.read ();        System.out.println ("Received:" + C);        Out.write (' s ');                Out.close ();        In.close ();        Server.close ();        Listen.close ();    }}

Client side:

/** *tcpclient * @author winty [email protected] * @version 2008-12-15 */import java.io.*;import java.net.*;class TCPClient {public    static void Main (string[] args) throws ioexception{        Socket client = new socket ("127.0.0.1", 5050);        InputStream in = Client.getinputstream ();        OutputStream out = Client.getoutputstream ();                Out.write (' C ');        char C = (char) in.read ();        System.out.println ("Received:" + C);        Out.close ();        In.close ();        Client.close ();    }}

Java Network framework:

  • MINA provides a very convenient framework for developing high-performance and high-availability Web applications, supporting TCP/UDP application development and serial communication programs based on Java NIO technology
  • Grizzly Design compared with the general NIO framework is different, the main difference is that both reading and writing are in the blocking way, and using temporary selector ; The threading model is highly configurable, It is not surprising, however, that the author describes the best way to handle read and write performance with a thread pool while running a selector main thread processing accept.
  • Nettty provides a set of event-based APIs to develop high-performance, manageable TCP/IP server or client applications. For high-performance network applications, Netty provides many basic features, such as readiness selection, thread pool, write buffer dos prevention, reusable buffering, and more.
  • The NiO Framework , built on top of the Java NiO Library, encapsulates much of the complexity of the original NIO. The NIO framework makes it easy to develop secure, high-performance Java network applications.
  • Quickserver A free open source Java library for fast creation of robust multithreaded, multi-client TCP server applications. With Quickserver, users can focus only on the application's logic/protocol.
  • Xsocket A lightweight NIO-based server framework for developing high-performance, scalable, multi-threaded servers. This framework encapsulates aspects such as threading, asynchronous read/write, and so on.
  • ioserver High-performance, easy-to-expand network framework, compared to the Apache Mina more lightweight, the source code is easier to read, the source code has a lot of detailed Chinese annotations, is a very good learning framework, The framework mainly focuses on solving the server-side program of mobile games in the Chinese market.

    Ioserver build a simple server routine (more detailed routines can download a routine package, or go to Wiki view) the server receives an integer from the client and adds a return to the client

  • Xnio A Java package that helps you simplify the development of NIO applications; provides a unique and easy-to-use API for combining blocking and non-blocking operations, even on the same channel It also allows you to take advantage of simple and low latency blocking I/O while also gaining the benefits of non-blocking I/O, and introduces a powerful callback-based interface that greatly simplifies traditional state-based Machine's non-blocking application and allows for a perfect balance between your application's throughput (throughput) and latency.


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Java Fundamentals Eight (network in java,c++)

Related Article

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.