Some time ago, I used to convert a Java Socket Client to a C # Socket Client, recently developed projects require the use of Java code to request the server to exchange data through a socket. net and some common Java technical points to make a record, because there is no socket server involved in the development of a large amount of concurrency, the requirements for subcontracting, sticking packets and some high performance have not been analyzed, this article only records the common usage methods between them and the methods for converting Java Socket to C # code.
I. Java SocketBefore jdk1.4, Java can only create sockets in synchronous mode, and asynchronous can only be asynchronous in multi-thread mode, java.net. the serversocket package can be used to create a socket processor for the server. The client uses java.net. socket Connection: Private serversocket Server = NULL; private Socket socket = NULL; inetaddress address = inetaddress. getbyname ("127.0.0.1"); server = new serversocket (, address); // listen to the window and wait for the connection socket = server. accept (); in this way, the accept () method of serversocket on the server will be blocked synchronously and wait for the client to connect. After receiving the socket connection request from the client, subsequent operations will be performed. The server uses Socket. getinputstream () to obtain the data stream input by the client. It reads the stream through socket. getoutputstream () and returns the data to the client. The Socket Client can use: Socket so = new socket ("127.0.0.1", 3000); inputstream is = so. getinputstream (); outputstream OS = so. getoutputstream (); To establish a socket connection. For example, you can directly send data to the server: OS. write (sendbyte ). After jdk1.4, the NIO package can be added to create non-blocking asynchronous socket server and client. java. NIO. channels. serversocketchannel is used to create a socket server, Java. NIO. channels. the socketchannel package is used to create a socket receiver or client. NIO. channels. selector manages the serversocketchannel of NiO. selector responds to client requests through events and registers events for selector. For example, it finds selectorselector = selector through the open () method. open (); serversocketchannel = serversocketchannel. open (); // register and receive request events to selectorserversocketchannel. register (S Elector, selectionkey. op_accept); events also include: selectionkey. op_read read event, selectionkey. op_write write operation event. After registering an event for the serversocketchannel, you can write a loop every time selector. when select () receives a value, it starts to determine what event it is and then executes the specific logic code according to the event. Create an asynchronous socket server code such as serversocketchannel = serversocketchannel. open (); // The configuration is non-blocking serversocketchannel. configureblocking (false); // obtain the server socket associated with the channel serversocket = serversocketchannel. socket (); // The server binds the IP port serversocket. BIND (New inetsocketaddress ("127.0.0.1", 3000); in this way, server listening is established through serversocketchannel, and then the following selector is used to add registration events for serversocketchannel to listen to various client events as the server. In Java, different packets are used for TCP and UDP respectively. UDP is handled using methods under the java.net. datagramsocket package.
Ii.. Net socket.. Net. net. in the ETS namespace, the asynchronous and synchronous methods can all use the socket class, and the choice of TCP and UDP is determined directly based on the socket constructor. For example: socket socket = new socket (addressfamily. interNetwork, sockettype. stream, protocoltype. TCP); protocoltype can be TCP or UDP. When UDP is used, sockettype must be used. the data format of the dgram type .. Net contains the server and client that encapsulate tcplistener and tcpclient to process TCP requests respectively, and the udpclient class is used to process the server and client of UDP requests. They are socket-based encapsulation. Tcplistener, tcpclient, and Java are similar in style. They use tcpclient. getstream () to return data streams and then operate on the Data. udpclient sends and receives data directly by sending and receive .. For example, ipendpoint hostep = new ipendpoint (IPaddress. parse ("127.0.0.1"), Port); socket = new socket (addressfamily. interNetwork, sockettype. stream, protocoltype. TCP); socket. BIND (hostep); socket. listen (500); Socket Client = socket. accept (); synchronously waits for a connected socket through the accept method. Of course, you can also asynchronously wait for the client connection request, you can use this socket to process data. It can use synchronous blocking receiving methods, such as: public int receive (byte [] buffer); Public int receive (byte [] buffer, int offset, int size, socketflags ); for synchronous receiving of client data, or asynchronous receiving of client data: APM mode: Public iasyncresult beginreceive (byte [] buffer, int offset, int size, socketflags, asynccallback callback, object state); or event Method: Public bool receiveasync (socketasynceventargs E); Data Processing Method: byte [] bytessendstr = new byte [1024 ]; Int bytes = client. receive (bytessendstr); string sendstr = encoding. utf8.getstring (bytessendstr, 0, bytes); sendstr = "server return:" + sendstr; bytessendstr = encoding. utf8.getbytes (sendstr); client. send (bytessendstr, bytessendstr. length, socketflags. none); the server side should receive the client data repeatedly until the integer returned by the received data is less than 1 to prevent reading the data from being completed and reading the results I think it is best to read the data in byte, generally, the socket may use the front field of the byte as the identifier, such as the length and type of the collected data. As a socket server, a large number of client socket requests must be processed at the same time. Therefore, it cannot be processed by a single thread. Each time an accept sends a client request, a thread is enabled for processing, there are a large number of threads to open, and sending data after the client request and the data returned by the server will lead to synchronization wait on the server side, resulting in a waste of thread resources. Therefore, the server generally uses an asynchronous method to process client requests.
Iii. Differences between Java Socket and C # socketGenerally, the differences are as follows: the method for creating a socket is different; the method for sending and receiving data is different; and the method for setting configuration parameters in Java is generally used ,. net is directly set as an attribute. The following describes several TCP methods, such as the method for creating a client in Java: Socket socket = new socket ("127.0.0.1", 3000 );. net client creation method: Socket newclient = new socket (addressfamily. interNetwork, sockettype. stream, protocoltype. TCP); // the server's IP address and port ipendpoint Ie = new ipendpoint (IPaddress. parse ("127.0.0.1"), 3000); newclient. connect (IE); Java: Socket socket = new socket ("127.0.0.1", 3000); inputstream is = socket. getinputstream (); outputstream OS = SOC Ket. getoutputstream (); // sends data to the OS. write (sendbyte); // read server data returnstr = inputstreamtostring (is );. net: byte [] MSG = encoding. utf8.getbytes (content); // newclient. receivetimeout = 10000; // directly send int bytessent = newclient. send (MSG); // directly receives the int bytesrec = newclient from the server. receive (data); specifies the socket parameter. For example, if Java sets the parameter: // allows the socket to be sent in a timely manner, the socket is not sent when no data is cached. settcpnodelay (true); // timeout value for receiving data socket. setsotimeout (30000 );. net corresponding to Jav The preceding settings of a are as follows: newclient. nodelay = true; newclient. receivetimeout = 30000; but if you want to convert a Java program to a C # program and keep the code style unchanged, you can use an open-source project: ikvm, its main Class Library: ikvm. openjdk. core. DLL, the internal namespace is basically the same as the Java package name, almost one-to-one correspondence, except for syntax, the writing methods of other Java class libraries are the same, therefore, the code written can be almost the same as that written in Java. I have roughly written some socket knowledge about Java and. net. If you have any questions, please correct me!
If reproduced, please indicate from: http://lawson.cnblogs.com/