Java Socket Programming

xiaoxiao2021-03-06  45

Java Socket Programming

Socket Transfer Mode

Sockets has two main ways: facing connected and unconnected. Connecting Sockets operations like a phone, they must establish a connection and one call. All things are arriving at the time of arrival. Like the order. Unconnected Sockets operation is like a mail delivery, no guarantee, multiple mail may not be the same as the order of departure.

Which mode is used in the end is the need to decide. If the reliability is more important, use the connection-oriented operation. For example, the file server requires the correctness and order of their data. If some data is lost The effectiveness of the system will be lost. Some servers, such as intermittently send some data blocks. If the data is lost, the server does not want to re-send again. Because it may have been out of time when the data arrives. Make sure the orderless and correctness of data requires additional memory consumption, additional costs will reduce the rate of response.

Unconnected Operation Using Data Reports. A datagram is a separate unit that contains all this delivery information. Imagine it into an envelope, it has a destination address and the content to send. This mode Socket does not need to connect a purpose of Socket, it just simply casts the datagram. Unconnected operation is fast and efficient, but data security is poor.

Connected operations use TCP protocols. Socket in this mode must get a connection with Socket with the destination before sending data. Once the connection is created, Sockets can use a stream interface: Open - Read - write - Close. All The information sent will be received in the same order at the other end. The connection-oriented operation is lower than the operational efficiency of the connection, but the data is more secure.

Sun has always been a supporter of network construction, so it is not surprising in Java. In fact, Java reduces the difficulty of establishing a sockets program. Each transmission mode is packaged in different classes. Connected The class will be first discussed by us.

Sockets has two main ways: facing connected and unconnected. Connecting Sockets operations like a phone, they must establish a connection and one call. All things are arriving at the time of arrival. Like the order. Unconnected Sockets operation is like a mail delivery, no guarantee, multiple mail may not be the same as the order of departure.

Which mode is used in the end is the need to decide. If the reliability is more important, use the connection-oriented operation. For example, the file server requires the correctness and order of their data. If some data is lost The effectiveness of the system will be lost. Some servers, such as intermittently send some data blocks. If the data is lost, the server does not want to re-send again. Because it may have been out of time when the data arrives. Make sure the orderless and correctness of data requires additional memory consumption, additional costs will reduce the rate of response.

Unconnected Operation Using Data Reports. A datagram is a separate unit that contains all this delivery information. Imagine it into an envelope, it has a destination address and the content to send. This mode Socket does not need to connect a purpose of Socket, it just simply casts the datagram. Unconnected operation is fast and efficient, but data security is poor.

Connected operations use TCP protocols. Socket in this mode must get a connection with Socket with the destination before sending data. Once the connection is created, Sockets can use a stream interface: Open - Read - write - Close. All The information sent will be received in the same order at the other end. The connection-oriented operation is lower than the operational efficiency of the connection, but the data is more secure.

Sun has always been a supporter of network construction, so it is not surprising in Java. In fact, Java reduces the difficulty of establishing a sockets program. Each transmission mode is packaged in different classes. Connected The class will be first discussed by us.

Java-oriented class

Recall one, a client sends a connection to a server socket that is listening. The client's sockets is built with the Socket class. The following program creates a client's socket and connects to a host:

Socket Clientsocket = New Socket ("Merlin", 80);

The first parameter is the name of the host you want to connect, the second parameter is the port number. A host name specifies the name of the purpose. The port number specifies which application is received. In our case, it must be specified 80, because it is the port of the default HTTP protocol. Additional well-known port columns in Table 9.1, see: well-known end:

Echo 7

Daytime 13

Daytime 13

FTP 21

Telnet 23

SMTP 25

Finger 79

HTTP 80

POP3 110

Because the Socket class is connected, it provides a streaming port for read-write. The classes in Java.IO can be used to access a connected Socket:

DataOutputStream Outbound = New DataOutputStream

ClientSocket.getOutputStream ());

DataInputStream Inbound = New DataInputStream (ClientSocket.getInputStream ()

);

Once the stream is established, the general flow operation can be done:

Outbound.WriteBytes ("Get / HTTP / 1.0 / R / N / R / N);

String responseline;

While ((responseline = inbound.readline ())! = null)

{

System.out.println (responseline);

}

The above applet requests a web page and display it. After the program is completed, the connection must be turned off.

Outbound.close ();

Inbound.close ();

Clientsocket.close ();

Note that the Socket stream must be closed first. All Socket streams must be closed before Socket is turned off. This applet is very simple, but all client programs must follow the basic steps below:

1. Establish a client Socket connection.

2. Get the stream of reading and writing of Socket.

3. Use the stream.

4. Turn off the stream.

5. Close the socket.

Using a server-side socket is just a bit complicated, it will be told below.

Server Sockets

The server is not actively establishing connection. Conversely, they are passively listening to a client connection, please call them. The server is built by class Serversocket. The following program has established a server-side socket and bind it to it 80 port:

Serversocket Serversocket = New ServerSocket (80, 5);

The first parameter is the port that the server is to listen to. The second parameter is an optional. API document describes this is a listening time, but the second parameter in the traditional Socket program is a listening depth. One server can be simultaneously A plurality of connection requests are received, but only one can be handled each time. Monitoring is an unassigned connection request queue. The above request creates a connection to handle the last five requests. If you have omitted a parameter, the default is 50.

Serversocket Serversocket = New ServerSocket (80, 5);

Once the socket has established and start listening to the connection, the connection will be created and put in the listening heap .accetp () method takes the connection in the heap.

Socket Clientsocket = Serversocket.accept ();

This method returns a client connection to the visitor dialog. The server itself cannot establish a conversation. Conversely, the server socket uses the accept () method to generate a new Socket. Server Socket still opens and arrange new connection requests .

Like the client Socket, the following step is established in the input and output stream:

DataInputStream Inbound = New DataInputStream (ClientSocket.getInputStream ()); DataOutputStream Outbound = New DataOutputStream (ClientSocket.getOutputStream ());

The general I / O operation can be used in new streams. It waits for a blank row before the server responds. When the session ends, the server shuts down the stream and the client socket. If there is no request in the queue, it will appear in the queue. What? That method will wait for the arrival. This behavior is called blocked .accept () method will block the server thread until a call arrive. After the 5 connection processing is complete, the server exits. Any in the queue The call will be canceled. All servers must have the following basic steps:

1. Create a server socket and start listening.

2. Use the accept () method to get a new connection.

3. Establish input and output flow.

4. Generate a session on the existing agreement.

5. Turn off the client stream and socket.

6. Go back to the second step or step.

7. Close the server socket

Repeat and concurrent server

All these calls can throw a unknownhostexception violation. If a computer is not connected to the DNS server, or the host does not find it, this violation will be thrown out. If a computer does not have an activated TCP / IP configuration, getLocalhost () Also throws a violation for failure.

Once an address is determined, the datagram can be sent. The following program transmits a string Socket:

String tosend = "this is the data to send!");

BYTE [] sendbuf = new byte [tosend.length ()];

Tosend.getbytes (0, Tosend.Length (), Sendbuf, 0);

DataGrampacket SendPacket = New DataGrampacket (Sendbuf, Sendbuf.Length,

Addr, port);

Clientsocket.send (SendPacket);

First, the string must be converted into a byte array. Then, a new DataGraMpacket instance must be established. Note the last two parameters of the builder. Because the package is to be sent, the address and port must be given. An applet It may be possible to know the address of its server, but how the server knows its client's address. When any package is received, the returned address and port will be decompressed and passed through the getaddress () and getport () method. Get it. This is how a server responds to a client package:

DataGrampacket SendPacket = New DataGrampacket (Sendbuf, Sendbuf.Length,

Recvpacket.getaddress (), recvpacket.getport ());

Serversocket.send (SendPacket);

Unlike connection-oriented operations, the datagram server server is actually more simpler than the datagram client:

Datagram

Basic steps for a datagram server:

1. Create a dataginary Socket on a specified port.

2. Wait to the package with the Receive method.

3. Use a specific protocol to respond to the received package.

4. Go back to the second step or continue in the second step.

5. Turn off the datagram.

Listing 9.3 demonstrates a simple data report response server. It will respond to the package it receives.

Listing 9.3. A simple datagram response server

Import java.io. *;

Import java.net. *;

Public Class SimpleDataGramserver

{

Public static void main (string [] args)

{

DataGramsocket Socket = NULL;

DataGrampacket Recvpacket, Sendpacket;

Try

{

Socket = New DataGramsocket (4545);

While (Socket! = NULL)

{

Recvpacket = New DataGrampacket (New Byte [512], 512);

Socket.Receive (Recvpacket);

Sendpacket = new datagrampacket (Recvpacket.getData (), recvpacket.getlength (),

Recvpacket.getaddress (), recvpacket.getport ());

Socket.send (SendPacket);

}

}

Catch (Socketexception SE)

{

System.out.println ("Error In SimpleDataGramserver:" SE);

}

Catch (IOEXCEPTION IOE)

{

System.out.println ("Error In SimpleDataGramserver:" IOE);

Simple web server

A simple web server will be constructed in this list 9.2. Of course, you must also improve the method and response event. Simple server does not analyze and store request heads. The new web server will analyze and store requests for future processing. Prepare. To reach this, you must have a class that contains HTTP requests.

HttpRequest class

Listing 9.5 lists a complete HTTPRequest class. This class must include all the information required for a request header.

Listing 9.5.HttpRequest class.

Import java.io. *;

Import java.util. *;

Import java.net. *;

Import namevalue;

/ **

* This class has an HTTP request for all information

* /

Public Class HttpRequest

{

Public String Version;

Public string method;

Public String file;

Public Socket Clientsocket;

Public DataInputStream Inbound;

Public NameValue Headerpairs [];

/ **

* Establish an instance of this class

* /

Public httprequest ()

{

Version = NULL;

Method = NULL;

File = NULL;

Clientsocket = NULL;

Inbound = NULL;

Inbound = NULL;

Headerpairs = new namevalue [0];

}

/ **

* Add a name / value to the core array

* /

Public void addnamevalue (String name, string value)

{

Try

{

NameValue Temp [] = new namevalue [Headerpairs.Length 1];

System.Arraycopy (Headerpairs, 0, Temp, 0, Headerpairs.Length);

Temp [Headerpairs.Length] = New NameValue (Name, Value);

Headerpairs = TEMP;

}

Catch (NullpointersRexception NPE)

{

System.out.println ("NullpointersReption while add name-value:

" NPE);

}

}

/ **

* Returned this class in the form of a string

* /

Public String Tostring ()

{

String S = Method " File " Version "/ N";

For (int x = 0; x

Return S;

}

}

The NameValue class simply stores two strings: Name and Value. When a new pair is to be added, a new array will be assigned. The new array accepts the old array and new members. Old array then Covered by a newly built object.

转载请注明原文地址:https://www.9cbs.com/read-80487.html

New Post(0)