The socket is simply a socket that is in the client's service and encapsulates a function and API.
Socket is the TCP/IP protocol encapsulation, the socket itself is not a protocol, but a call interface (API), through the socket, we can use the TCP/IP protocol.
Communication between the server and the client is required first. Client: Socket s=new socket ("127.0.0.1", 9999); Enter the IP address and port number.
Service end: ServerSocket server=new ServerSocket (9999); Socket s=server.accept (); Get the port number. and data.
Client:
Package com.xu.chat;
Import java.io.IOException;
Import Java.io.PrintWriter;
Import Java.net.Socket;
Import Java.util.Scanner;
public class Client {
public static void Main (string[] args) {
Socket S=null;
try {
S=new Socket ("127.0.0.1", 9999);
PrintWriter p=new PrintWriter (S.getoutputstream (), true);
Scanner sc=new Scanner (system.in);
while (Sc.hasnext ()) {
String S1=sc.nextline ();
P.println (S1);
}
Sc.close ();
P.flush ();
P.close ();
catch (Exception e) {
Todo:handle exception
E.printstacktrace ();
}finally{
try {
S.close ();
catch (IOException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}
}
}
Service:
Package com.xu.chat;
Import Java.io.BufferedReader;
Import java.io.IOException;
Import Java.io.InputStreamReader;
Import Java.net.ServerSocket;
Import Java.net.Socket;
public class Server {
public static void Main (string[] args) {
ServerSocket Server=null;
Socket S=null;
try {
Server=new ServerSocket (9999);
S=server.accept ();
Boolean flag=true;
BufferedReader br=new BufferedReader (New InputStreamReader (S.getinputstream ()));
System.out.println (BR);
while (flag) {
String S1=br.readline ();
if (S1.trim (). toLowerCase (). Equals ("Q")) {
SYSTEM.OUT.PRINTLN ("Client doesn't want to play anymore.") ");
Flag=false;
}else{
System.out.println (S1);
}
}
Br.close ();
catch (IOException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}finally{
try {
S.close ();
Server.close ();
catch (IOException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}
}
}
Summary: Socket usage is far more than that in the bottom of the Java EE also has a lot of applications, and later to more in-depth understanding.
the first part, the understanding of the concept
1, what is socket.
Socket, also known as "socket", is a system-provided method for network communication. Its essence is not a protocol, it does not specify how the computer should deliver the message, but gives the programmer a message-sending interface, the programmer uses this interface to provide the method to send and receive messages.
The socket describes an IP, port pair. It simplifies the programmer's operations, knows each other's IP and port can send messages to each other, and then the server side to handle the sent messages. Therefore, the socket must contain the dual-hair of the communication, that is, the client and service side (server).
2, the socket communication process.
Each application, or service, has a port. such as DNS 53 port, HTTP 80 port. We can request DNS requests to query information, because the DNS server is listening to 53 ports at all times, and when we receive our query request, we can return the IP information we want. So, in terms of programming, you should include the following steps:
1 The service end uses the socket listening port;
2 The client initiates the connection;
3 The service side returns the information, establishes the connection, starts the communication;
4 Client, service end disconnect.
3. How to set up the connection between the socket.
The following procedure is represented in code:
Server End:
1 intport = 2000;
2 Ipendpointserverep = new IPEndPoint (ipaddress.any,port);
3 Socketserver = new Socket (AddressFamily.InterNetwork, sockettype.stream,protocoltype.tcp);
4 server. Bind (SERVEREP);
5 server. Listen (0);
Client side:
1 intport = 2000;
2 Ipaddressserverip = Ipaddress.parse ("192.168.1.100");
3 Ipendpointep = new IPEndPoint (server,port);
4 Socketserver = new Socket (AddressFamily.InterNetwork, sockettype.stream,protocoltype.tcp);
5 server. Bind (EP);
When the server receives a connection from the client, a new socket is needed to handle the remote information.
The following section of code should be on the server side:
1 socketclient = server. Accept ();
The above very simple lines of code, will be used in future network programming, there will be synchronous communication, asynchronous communication, threads, delegates and events and so on
The second part, the difference between the agreements
TCP/IP SOCKET HTTP
The seven layers of the network are the physical layer, the data link layer, the network layer, the Transport layer, the session layer, the presentation layer and the application layer respectively.
The physical layer, the data link layer and the network layer are usually called the media layer, which is the object of the network engineers.
The transport layer, the session layer, the presentation layer and the application layer are called the host layer, which is the content that the user faces and cares about.
HTTP protocol corresponds to application tier
TCP protocol corresponds to transport layer
IP protocol corresponds to the network layer
There is no comparability of the three by nature. Moreover, the HTTP protocol is based on TCP connections.
TCP/IP is a Transport layer protocol that mainly addresses how data is transmitted over the network, while HTTP is an application layer protocol that mainly addresses how data is packaged.
When we transfer data, we can use only the transport layer (TCP/IP), but in that case, because there is no application layer, it can not recognize the data content, if you want to make the transmission of data meaningful, you must use the Application layer protocol, the application layer protocol, there are HTTP, FTP, Telnet You can also define the application layer protocol yourself. The web uses HTTP as a transport Layer protocol to encapsulate HTTP text information, and then use TCP/IP as a Transport layer protocol to send it to the network.
Socket is the TCP/IP protocol encapsulation, the socket itself is not a protocol, but a call interface (API), through the socket, we can use the TCP/IP protocol.
HTTP and Socket Connection differences
I believe that many novice mobile phone networking development friends want to know what is the difference between HTTP and socket connection, hope that through their own simple understanding can help beginners.
1, TCP connection
To understand the socket connection, first understand the TCP connection. The mobile phone can use the networking function because the mobile phone at the bottom of the implementation of the TCP/IP protocol, the mobile phone terminal through the wireless network to establish a TCP connection. The TCP protocol can provide an interface to the upper layer network, so that the transmission of the upper layer network data is based on the "No Difference" network.
Establishing a TCP connection requires a "three handshake":
First handshake: The client sends the SYN packet (SYN=J) to the server, and enters the Syn_send state, waiting for the server to confirm;
Second handshake: The server received the SYN packet, must confirm the customer's SYN (ACK=J+1), but also send a SYN packet (syn=k), that is Syn+ack packet, at this time the server into the SYN_RECV state;
Third handshake: The client receives the server Syn+ack packet, sends the confirmation packet ack (ACK=K+1) to the server, this packet sends completes, the client and the server enters established state, completes three times handshake.
Handshake process in the packet is not included in the data, three times after the handshake, the client and the server began to transfer data officially. Ideally, once a TCP connection is established, the TCP connection is maintained until either side of the communication actively closes the connection. When disconnected, both the server and the client can initiate a request to disconnect the TCP connection, and the disconnect process requires a "four handshake" (the process is not fine, that is, the server and client interaction, the final determination of the disconnect)
2, HTTP connection
HTTP protocol, the Hypertext Transfer Protocol (Hypertexttransfer Protocol), is the foundation of Web networking and one of the common protocols of mobile networking, and HTTP protocol is an application based on TCP protocol.
The most notable feature of HTTP connections is that each request sent by the client requires a server loopback response, and the connection is actively released after the request is completed. The process from establishing a connection to closing a connection is called a "once connection."
1 in HTTP 1.0, each request from the client requires a separate connection to be established, and the connection is automatically released after the request has been processed.
2 in HTTP 1.1, you can handle multiple requests in a single connection, and multiple requests can overlap, without waiting for a request to end before sending the next request.
Because HTTP actively frees connections after each request, HTTP connections are a "short connection" that requires constant connection requests to the server to keep the client program online. The usual practice is to not need to get any data immediately, the client also maintains every fixed time to send the server a "Stay Connected" request, the server after receiving the request to the client reply, indicating that the client "online." If the server is unable to receive the client's request for a long time, the client is considered "offline" and if the client cannot receive a reply from the server for a long time, the network has been disconnected.
3, Socket principle
3.1 Socket (socket) concept
Socket (socket) is the cornerstone of communication, is the basic operating unit of network communication that supports TCP/IP protocol. It is the abstract representation of the endpoint in network communication, including the five kinds of information that must be used for network communication: The Protocol of the connection, the IP address of the local host, the protocol port of the local process, the IP address of the remote host, and the protocol port of the remote process.
When the application layer is communicating through the transport layer, TCP encounters problems that simultaneously provide concurrent services for multiple application processes. Multiple TCP connections or multiple application processes may need to transmit data through the same TCP protocol port. To differentiate between different application processes and connections, many computer operating systems provide socket (socket) interfaces for applications to interact with the TCP/IP protocol. The application layer can communicate with the transport layer through the socket interface to distinguish the communication from different application processes or network connections, and realize the concurrent service of data transmission.
3.2 Establishing a socket connection
Establishing a socket connection requires at least a pair of sockets, one running on the client, called Clientsocket, and the other running on the server side, called ServerSocket.
The connection process between sockets is divided into three steps: Server listening, client requests, connection confirmation.
Server listening: server-side sockets do not locate specific client sockets, but are in the state of waiting for connections, real-time monitoring of network status, waiting for client connection requests.
Client request: Refers to the client socket to make a connection request, the target to be connected is the server-side socket. To do this, the socket for the client must first describe the socket of the server to which it is connecting, indicate the address and port number of the server-side socket, and then make a connection request to the server-side socket.
Connection confirmation: When the server-side socket supervisor hears or says that a connection request for a client socket is received, in response to the client socket request, create a new thread, the server-side socket description to the client, once the client confirmed this description, the two sides formally establish a connection. While the server-side socket continues to be listening, it continues to receive connection requests from other client sockets.
4. Socket connection and TCP connection
When creating a socket connection, you can specify the transport layer protocol used, which can support different transport layer protocols (TCP or UDP), which is a TCP connection when the TCP protocol is used to connect.
5, Socket connection and HTTP connection
Since the socket connection is typically a TCP connection, once the socket connection is established, the two sides of the communication can start sending the data to each other until the connection is disconnected. But in the actual network application, communication between clients to the server often needs to traverse multiple intermediate nodes, such as routers, gateways, firewalls, and so on, most firewalls will shut down a long inactive connection and cause the Socket connection to disconnect, so it needs to be polled to tell the network that the connection is active.
The HTTP connection uses a "request-response" approach, not only to establish a connection when the request is made, but also to require the client to make a request to the server before the server can reply to the data.
In many cases, a server-side initiative is required to push data to the client, keeping the client and server data in real-time and synchronized. At this point if the two sides to establish a socket connection, the server can directly transfer data to the client; If the two sides establish an HTTP connection, the server needs to wait for the client to send a request before the data back to the client, so the client sends a connection request to the server, not only can remain online, It is also the "ask" whether the server has new data, and if so, pass the data to the client.
What does an HTTP connection mean
HTTP is an object-oriented protocol belonging to the application layer, which is suitable for distributed hypermedia information System because of its simple and fast way. It was proposed in 1990, after several years of use and development, has been continuously improved and expanded. Currently used in the WWW is the sixth edition of Http/1.0, http/1.1 is in progress, and Http-ng (Next Generation of HTTP) has been proposed. (The agreement is a global positioning.) )
The core--http Protocol of WWW
As we all know, the basic protocol of Internet is TCP/IP protocol, currently widely used FTP, Archie gopher and so on is based on TCP/IP Protocol Application layer protocol, different protocols correspond to different applications. The main protocol used by WWW Server is HTTP protocol, that is, hyper-stylistic transfer protocol. Because the HTTP protocol supports services that are not limited to WWW or other services, the HTTP protocol allows users to access different services under a unified interface, such as FTP, Archie, SMTP, NNTP, and so on. In addition, the HTTP protocol can also be used for name servers and distributed object management.
Introduction to 2.1 HTTP protocol
HTTP is an object-oriented protocol belonging to the application layer, which is suitable for distributed hypermedia information System because of its simple and fast way. It was proposed in 1990, after several years of use and development, has been continuously improved and expanded. Currently used in the WWW is the sixth edition of Http/1.0, http/1.1 is in progress, and Http-ng (Next Generation of HTTP) has been proposed.
The main features of the HTTP protocol can be summarized as follows:
1. Support client/server mode.
2. Simple and quick: When a client requests a service from a server, it simply transmits the request method and path. The request method usually has a get, a head, a POST. Each method prescribes a different type of customer contact with the server. Because the HTTP protocol is simple, the HTTP server's program is small, so the communication speed is very fast.
3. Flexible: HTTP allows the transfer of any type of data object. The type being transferred is marked by Content-type.
4. No connection: The implication of no connection is to limit the processing of only one request per connection. When the server finishes processing the customer's request and receives a reply from the customer, the connection is disconnected. In this way, the transmission time can be saved.
5. Stateless: The HTTP protocol is a stateless protocol. Stateless means that the protocol has no memory capability for transaction processing. A lack of status means that if the preceding information is required for subsequent processing, it must be retransmission, which may result in an increase in the amount of data transmitted per connection. On the other hand, it responds faster when the server does not need prior information.
Several important concepts of 2.2 HTTP protocol