Java Network Programming principle of socket __ programming

Source: Internet
Author: User
Tags readline sin thread class

One, two main problems in network programming
One is how to accurately locate the network on one or more hosts, and the other is to find the host after the reliable and efficient data transmission.
In the TCP/IP protocol, the IP layer is mainly responsible for the location of the network host, the routing of Data transmission, the IP address can uniquely determine a host on the Internet.
The TCP layer provides reliable or unreliable data transmission mechanism for application, which is the main object of network programming, and generally does not need to care about how the IP layer handles the data.
At present, the more popular network programming model is client/server (c/s) structure. That is, both sides of the communication wait for the customer to request and respond as a server. The customer applies to the server when the service is needed. The server is always running as a daemon, listening to the network port, once the customer request, will start a service process to ring should customers, while their own continue to monitor the service port, so that later customers can also be timely access to services.
two, two types of transport protocol: TCP;UDP
TCPIstranfer Control ProtocolShort, is a connection-oriented protocol to ensure reliable transmission. Through the TCP protocol transmission, obtains is a sequential error-free data stream. A connection must be established between the pair of two sockets of the sender and receiver to communicate on the basis of the TCP protocol, and when one socket (usually the server socket) waits for the connection to be made, another socket can require a connection. Once these two sockets are connected, they can transmit data in both directions, and both can send or receive operations.
UDPIsUser Datagram ProtocolThe abbreviation, is a connectionless protocol, each datagram is a separate information, including the full source address or destination address, it on the network on any possible path to the destination, so whether to reach the destination, the time to arrive at the destination and the correctness of the content is not guaranteed.
Comparison:
UDP:1, the full address information is given in each datagram, so there is no need to establish a connection between the sender and the receiver.
2,UDP is limited in size when transmitting data, each transmitted datagram must be limited to 64KB.
3,UDP is an unreliable protocol in which datagrams sent by the sender do not necessarily reach the receiver in the same order
TCP:1, connection-oriented protocol, in the socket between the data transmission must establish a connection, so in TCP need to connect
Time.
2,TCP Transmission data size limit, once the connection is established, both sides of the socket can be in uniform format transmission of large
Data.
3,TCP is a reliable protocol that ensures that the receiver is fully and correctly getting all the data sent by the sender.
Application:
1,TCPThere is strong survivability in network communications, such as remote Connection (Telnet) and file Transfer (FTP), which require indefinite length of data to be transmitted reliably. But the reliable transmission is to pay the price, the test of the correctness of the data content must occupy the processing time of the computer and the bandwidth of the network, so the TCP transmission efficiency is not as high as UDP.
2,UDPIt is simple to operate and requires less monitoring, so it is usually used for client/server applications in decentralized systems with high reliability on the LAN. For example, video conferencing system, does not require audio and video data is absolutely correct, as long as the consistency can be guaranteed, in this case, the obvious use of UDP is more reasonable.

Three, Java network programming based on socket
1, what is socket
Two programs on the network realize the exchange of data through a two-way communication connection, one end of this two-way link is called a socket. The socket is typically used to implement a connection between the client and the service party. The socket is a very popular programming interface for the TCP/IP protocol, and a socket is uniquely determined by an IP address and a port number.
However, the type of protocol supported by the socket is not only TCP/IP, so there is no connection between the two. In the Java environment, socket programming mainly refers to the network programming based on TCP/IP protocol.
The process of 2,socket communication
Server-side Listen (listening) whether a port has a connection request, the client sends a connect request to the server side, and the server sends back the ACCEPT (accepted) message to the client side. A connection is established. Both the server end and the client side can communicate with each other by means of send,write.
For a fully functional socket, include the following basic structure, which includes the following four basic steps:
(1) Create socket;
(2) Open the input/out stream connected to the socket;
(3) Read/write the socket according to a certain protocol;
(4) Close the socket. (In practice, not to use the display of closed, although many articles are recommended, but in my program, because the program itself is relatively simple, the requirements are not high, so did not cause any impact.) )
3, create the socket
Create a socket
Java provides two classes of sockets and ServerSocket in Package java.net, respectively, to represent two-way connected clients and services. This is one of two very good packaged classes and is easy to use. The method is constructed as follows:
Socket (inetaddress address, int port);
Socket (inetaddress address, int port, Boolean stream);
Socket (String host, int prot);
Socket (String host, int prot, Boolean stream);
Socket (SocketImpl impl)
Socket (String host, int port, inetaddress localaddr, int localport)
Socket (inetaddress address, int port, inetaddress localaddr, int localport)
ServerSocket (int port);
ServerSocket (int port, int backlog);
ServerSocket (int port, int backlog, inetaddress bindaddr)
wherein address, host, and port are the IP addresses, host names, and port numbers of the other side of the two-way connection, and the stream indicates whether the socket is a stream socket or datagram socket,localport that represents the port number of the local host. Localaddr and BINDADDR are the address of the local machine (ServerSocket host address), Impl is the parent of the socket, which can be used to create serversocket and to create sockets. Count indicates the maximum number of connections that the server can support. For example:
Socket client = new Socket ("127.0.01.", 80);
ServerSocket Server = new ServerSocket (80);
Note that you must be careful when choosing a port. Each port provides a specific service, and only the correct port is given to obtain the appropriate service. The port number for the 0~1023 is reserved for the system, for example, the port number of the HTTP service is the port number of the 80,telnet service is 23, so when we select the port number, it is best to select a number greater than 1023 to prevent conflicts.
If an error occurs when the socket is created, a ioexception is generated and must be processed in the program. So in creating a socket or serversocket you have to catch or throw an exception.
4, Simple Client/server program
1. Client program
Import java.io.*;
Import java.net.*;
public class Talkclient {
public static void Main (String args[]) {
try{
Socket socket=new socket ("127.0.0.1", 4700);
Shanben 4700 Port to issue customer request
BufferedReader sin=new BufferedReader (New InputStreamReader (system.in));
Constructing BufferedReader objects from System standard input devices
PrintWriter os=new PrintWriter (Socket.getoutputstream ());
The output stream is obtained from the socket object and the PrintWriter object is constructed
BufferedReader is=new BufferedReader (New InputStreamReader (Socket.getinputstream ()));
The input stream is obtained from the socket object and the corresponding BufferedReader object is constructed
String ReadLine;
Readline=sin.readline (); Read a string from System standard input
while (!readline.equals ("Bye")) {
Stop the loop if the string read from the standard input is "bye"
Os.println (ReadLine);
To output a read-from-system-standard input string to the server
Os.flush ();
Refreshes the output stream so that the server receives the string immediately
System.out.println ("Client:" +readline);
Print read-in string on system standard output
System.out.println ("Server:" +is.readline ());
Read a string from server and print to standard output
Readline=sin.readline (); Read a string from System standard input
}//Continue cycle
Os.close (); Turn off the socket output stream
Is.close (); Close the socket input stream
Socket.close (); Close socket
}catch (Exception e) {
System.out.println ("Error" +e); Error, print error message
}
}
}
2. Server-side Programs
Import java.io.*;
Import java.net.*;
Import Java.applet.Applet;
public class talkserver{
public static void Main (String args[]) {
try{
ServerSocket Server=null;
try{
Server=new ServerSocket (4700);
Create a ServerSocket to monitor client requests on port 4700
}catch (Exception e) {
System.out.println ("Can not be listen to:" +e);
Error, print error message
}
Socket Socket=null;
try{
Socket=server.accept ();
Use Accept () to block waiting for a customer request with a customer
When the request arrives, a socket object is generated and continues to execute
}catch (Exception e) {
System.out.println ("Error.") +E);
Error, print error message
}
String Line;
BufferedReader is=new BufferedReader (New InputStreamReader (Socket.getinputstream ()));
The input stream is obtained from the socket object and the corresponding BufferedReader object is constructed
PrintWriter Os=newprintwriter (Socket.getoutputstream ());
The output stream is obtained from the socket object and the PrintWriter object is constructed
BufferedReader sin=new BufferedReader (New InputStreamReader (system.in));
Constructing BufferedReader objects from System standard input devices
System.out.println ("Client:" +is.readline ());
Print a string read from the client on standard output
Line=sin.readline ();
Read a string from standard input
while (!line.equals ("Bye")) {
If the string is "Bye", Stop the Loop
Os.println (line);
Output the string to the client
Os.flush ();
Refreshes the output stream so that the client receives the string immediately
System.out.println ("Server:" +line);
Print read-in string on system standard output
System.out.println ("Client:" +is.readline ());
Reads a string from the client and prints it to the standard output
Line=sin.readline ();
Read a string from System standard input
}//Continue cycle
Os.close (); Turn off the socket output stream
Is.close (); Close the socket input stream
Socket.close (); Close socket
Server.close (); Close ServerSocket
}catch (Exception e) {
System.out.println ("Error:" +e);
Error, print error message
}
}
}
5, support multi-customer Client/server program
The previous Client/server program can only implement a conversation between a server and a customer. In practice, a permanent program is often run on a server that can receive requests from multiple clients and provide the appropriate services. In order to realize the function of providing service to multiple customers in server, the above program needs to be reformed, and multi-client mechanism is realized by multithreading. The server always listens for client requests on the specified port, and once the client requests are tapped, the server initiates a dedicated service thread to respond to the customer's request, and the server itself enters the listening state immediately after the thread is started, waiting for the next customer to arrive.
ServerSocket Serversocket=null;
Boolean listening=true;
try{
Serversocket=new ServerSocket (4700);
Create a ServerSocket to monitor client requests on port 4700
}catch (IOException e) {}
while (listening) {//Forever loop Listening
New Serverthread (Serversocket.accept (), Clientnum). Start ();
Listen to the client request, according to the resulting socket object and
The customer count creates a service thread and starts the
clientnum++; Increase Customer count
}
Serversocket.close (); Close ServerSocket
Design Serverthread Class
public class Serverthread extends thread{
Socket Socket=null; To save the socket object associated with this thread
int clientnum; Save account count for this process
Public serverthread (Socket socket,int num) {//constructor
This.socket=socket; Initializing the socket variable
clientnum=num+1; Initializing Clientnum variables
}
public void Run () {//thread body
try{//here to implement data acceptance and sending}
Four, datagram communication
TCP/IP protocol in the transport layer in addition to the TCP protocol there is a UDP protocol, compared to the application of UDP is not as wide as TCP, several standard application layer protocol HTTP,FTP,SMTP ... The TCP protocol is used. However, the UDP protocol can be applied to situations that require strong real-time interactivity, such as network games, video conferencing, and so on.
1, what is datagram
The datagram (Datagram) is just like the mail system in the daily life, cannot guarantee to send reliably, but the link-oriented TCP is like the telephone, both sides can affirm the other side to receive the information.
TCP, reliable, unlimited transmission size, but need to connect the build time, error control overhead.
UDP, unreliable, error control overhead, transmission size limited to 64K below, no need to establish a connection.
2,datagram use
Packagejava.netTwo classes are available inDatagramsocketAndDatagrampacketUsed to support datagram communication, Datagramsocket is used to establish a communication connection between programs that transmits datagrams, and datagrampacket is used to represent a datagram.
the construction method of Datagramsocket:
Datagramsocket ();
Datagramsocket (int prot);
Datagramsocket (int port, inetaddress laddr)
Where port indicates the port number used by the socket, and if the port number is not indicated, connect the socket to the available port on the local host. LADDR indicates an available local address. To ensure that no port conflicts occur when the port number is given, the SocketException class exception is generated. Note: All two of the above constructs are declared to discard the runtime exception socketexception, which must be processed, or captured, or declared discarded.
When the Client/server program is written by means of a datagram, it is necessary to establish a Datagramsocket object to receive or send the datagram, and then use Datagrampacket object as the carrier of data transmission, whether on the client side or the service side.
the construction method of Datagrampacket:
Datagrampacket (byte buf[],int length);
Datagrampacket (byte buf[], int length, inetaddress addr, int port);
Datagrampacket (byte[] buf, int offset, int length);
Datagrampacket (byte[] buf, int offset, int length, inetaddress address, int port);
Among them, the data in the buf, length for the data in the datagram, addr and port aim for the address of eyesight, offset indicates the amount of data reported displacement.
Before receiving data, you should use the first method above to generate a Datagrampacket object, giving the buffer and its length of the received data. Then call the Datagramsocket method receive () to wait for the datagram to arrive, and receive () will wait until a datagram is received.
Datagrampacket packet=new Datagrampacket (BUF, 256);
Socket.receive (packet);
Before sending the data, you also want to be a new Datagrampacket object, and then use the second method above to give a full destination address, including IP address and port number, while giving the buffer for sending data. The sending data is implemented via the Datagramsocket method Send (), and send () is searched for the destination address of the datagram to pass the datagram.
Datagrampacket packet=new datagrampacket (buf, length, address, port);
Socket.send (packet);
In constructing the data timekeeping, the InetAddress class parameters are given. Class inetaddress is defined in the package java.net to represent an Internet address, and we can use the class method provided by it Getbyname () to obtain the IP address of the host from a string representing the host name, and then obtain the appropriate address information.
3, broadcast communication with datagram (MulticastSocket)
Datagramsocket only allows datagrams to send a destination address, the Java.net package provides a class MulticastSocket that allows datagrams to be sent to all customers on that port on a broadcast basis. MulticastSocket is used on the client to listen for data that the server broadcasts.
1. Client procedure: Multicastclient.java
Import java.io.*;
Import java.net.*;
Import java.util.*;
public class Multicastclient {
public static void Main (String args[]) throws IOException
{
MulticastSocket socket=new MulticastSocket (4446);
Create a 4446-port broadcast socket
InetAddress address=inetaddress.getbyname ("230.0.0.1");
Get 230.0.0.1 's address information
Socket.joingroup (address);
Bind a broadcast socket to an address using joingroup ()
Datagrampacket packet;
for (int i=0;i<5;i++) {
Byte[] Buf=new byte[256];
Create buffer
Packet=new Datagrampacket (buf,buf.length);
Create a Receive datagram
Socket.receive (packet); Receive
String Received=new string (Packet.getdata ());
Gets the byte array from the received datagram,
And this constructs a string object
System.out.println ("Quote of Themoment:" +received);
Print the resulting string
}//Cycle 5 times
Socket.leavegroup (address);
Unbind a broadcast socket from an address
Socket.close (); Turn off broadcast sockets
}
}
2. Server-side program: Multicastserver.java
public class multicastserver{
public static void Main (String args[]) throws Java.io.IOException
{
New Multicastserverthread (). Start ();
Start a server thread
}
}
3. Procedure Multicastserverthread.java
Import java.io.*;
Import java.net.*;
Import java.util.*;
public class Multicastserverthread extends Quoteserverthread
Inherit from quoteserverthread new Server thread class Multicastserverthread
{
Private long five_second=5000; Define constants, 5 seconds
Public Multicastserverthread (String name) throws IOException
{
Super ("Multicastserverthread");
Call the parent class, which is the Quoteserverthread constructor
}
public void Run ()//overriding the thread body of the parent class
{
while (morequotes) {
To determine whether to continue the loop based on the flag variable
try{
Byte[] Buf=new byte[256];
Create buffer
String Dstring=null;
if (in==null) dstring=new Date (). toString ();
If opening a file fails while initializing,
Then use the date as the string to be routed
else Dstring=getnextquote ();
Otherwise, the calling member function reads the string from the file
Buf=dstring.getbyte ();
Converts a string to an array of bytes to send send it
InetAddress group=inetaddress.getbyname ("230.0.0.1");
Get 230.0.0.1 's address information
Datagrampacket packet=new Datagrampacket (buf,buf.length,group,4446);
Creates a Datagrampacket object based on the buffer, broadcast address, and port number
Socket.send (packet); Send the packet
try{
Sleep ((Long) (Math.random () *five_seconds));
Randomly waiting for a period of time, between 0-5 seconds
}catch (Interruptedexception e) {}//exception handling
}catch (IOException e) {//exception handling
E.printstacktrace (); Print Error stack
Morequotes=false; End Loop Flag
}
}
Socket.close (); Turn off the broadcast socket interface
}
}

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.