PHP Socket Programming

Source: Internet
Author: User
Tags bind ftp function prototype interface variables php code socket web services

Socket

The image description of the socket agreement
1. One is the engine (Socket), providing the ability of network communication
One is a sedan (Http) that provides a specific way

The original meaning of 2.socket is "hole" or "socket". Here as a 4BDS UNIX process communication mechanism, take the latter meaning. The socket is very similar to a telephone socket. Take a national telephone network for example. Telephone calls are equivalent to each other 2 processes of communication, the area code is its network address, a unit in the area of the switch equivalent to a host, the host assigned to each user's internal number is equivalent to the socket number. Any user prior to the call, first to occupy a telephone, equivalent to the application of a socket, and to know the other person's number, equivalent to the other side has a fixed socket. Then dial the call to the other side, which is equivalent to sending a connection request (if the other person is not in the same zone, and dial the other area code, equivalent to the network address). If the other party is present and free (equivalent to another host of communication and can accept the connection request), pick up the phone microphone, the two sides can officially call, the equivalent of successful connection. Both sides of the call process, is a direction of the telephone signal and the other from the phone to receive signals, the equivalent of sending data to the socket and receive data from the socket. After the call is over, one side hangs up the telephone equivalent of closing the socket and undoing the connection.
In the telephone system, the average user can only feel the presence of the local telephone and the other phone number, the process of establishing the call, the process of voice transmission and the technical details of the entire telephone system are transparent to him, which is very similar to the socket mechanism. Socket uses the network communication facilities to achieve process communication, but it is not concerned about the details of the communication facilities, as long as the communication facilities to provide sufficient communication capacity, it is satisfied.
So far, we have an intuitive description of the socket. Abstract, the socket essentially provides the endpoint of the process communication. Before a process communicates, both parties must first create an endpoint, otherwise there is no way to establish a connection and communicate with each other. Just like before the phone call, both sides must each have a telephone. Inside the net, each socket is described in a semi-relevant description:
(Protocol, local address, local port)
A complete socket has a local unique socket number, which is allocated by the operating system.
Most importantly, the socket is designed for client/server models and provides different socket system calls for client and server programs. Customers randomly apply for a socket (equivalent to a person who wants to call can dial a call on any network phone), the system assigns a socket number; The server has a globally recognized socket, and any customer can send a connection request and information request to it ( The equivalent of a called phone has a phone number known to the caller).
The socket uses client/server mode to skillfully resolve the problem of establishing a communication connection between processes. It is important that server sockets are partially related to the global. Readers may wish to consider how to establish communication between two completely random user processes. If the two sides of the communication do not have either side of the socket fixed, it is like the two sides of the phone do not know each other's phone number, to call is impossible.
-----
The socket interface is the most widely used method of accessing the Internet. If you have a host that just matches the TCP/IP protocol, its IP address is 202. 120.127. 201, it is obvious that the connection cannot be established by performing FTP 202.120.127.201 on another host or on the same host. The FTP service software is not running for the "202.120.127.201" host. Also, run browsing software such as Netscape on another or the same host, and enter "http://202.120.127.201" and cannot establish a connection. Now, if you run an FTP service software on this host (the software will open a socket and bind it to Port 21), run a Web service software on this host (the software will open another socket and bind it to port 80). In this way, FTP 202.120.127.201 is performed on another host or on the same host, and the FTP client software connects to and talks to the socket on the host provided by the FTP service software via port 21. When you enter "http://202.120.127.201" in Netscape, you will use 80 ports to call the socket provided by the Web Services software on the host, and to connect and talk to it.
There are many such hosts on the internet that typically run multiple service software while providing several services. Each service opens a socket and is bound to a port where different ports correspond to different services. Socket, as its English intended, like a porous socket. A host is like a room full of sockets, each socket has a number, and some outlets provide 220 volts AC, some provide 110 volts AC, and some provide cable TV programs. Customer software will plug into different number of sockets, you can get different services.
-----
1. What is a socket the so-called socket is often referred to as "socket", which describes the IP address and port, and is the handle of a communication chain. The application usually sends a request to the network through a "socket" or answers a network request. To J2sdk-1. 3 For example, the socket and ServerSocket class libraries are located in Java. NET package. ServerSocket is used on the server side and the socket is used when establishing a network connection. When the connection succeeds, both ends of the application produce an instance of the socket, manipulating the instance to complete the desired session. For a network connection, sockets are equal and do not differ, not because of the different levels that occur on the server or on the client side. Either the socket or the ServerSocket their work is done through the SocketImpl class and its subclasses.
Important socket Api:java. NET. The socket inherits from Java. Lang. Object, there are eight constructors, its methods are not many, the following describes the most frequently used three methods, other methods you can see JDK-1. 3 documents.
The Accept method is used to generate "blocking" until a connection is accepted and a client's socket object instance is returned. "Blocking" is a term that allows a program to run temporarily "stay" in this place until a session is generated, and then the program continues; usually "blocking" is generated by loops.
The getInputStream method obtains the network connection input and returns a Iutputstream object instance.
The other end of the Getoutputstream method connection is entered and a OutputStream object instance is returned. Note that both the getInputStream and Getoutputstream methods produce a ioexception that must be captured because the stream object they return is usually used by another stream object.
2. How to develop a server-client model of the program development principle:
Server, using ServerSocket to listen to the specified port, the port can be arbitrarily specified (because the port under 1024 is usually reserved port, in some operating systems are not free to use, so it is recommended to use a port greater than 1024), waiting for customer connection request, after the client connected, the session generated , and close the connection after the session completes.
Client, use the socket to issue a connection request to a port on one of the servers on the network, open the session once the connection is successful, and close the socket after the session completes. The client does not need to specify an open port, typically temporarily, dynamically allocating more than 1024 ports.
The socket interface is a TCP/IP network Api,socket interface that defines many functions or routines that programmers can use to develop applications on a TCP/IP network. To learn about TCP/IP network programming on the Internet, you must understand the socket interface. The socket interface designer first placed the interface inside the UNIX operating system. If you understand the input and output of UNIX systems, you can easily understand the socket. Socket data transfer In a network is a special i/o,socket and a file descriptor. The socket also has a function call socket () that is similar to opening a file, which returns an integral socket descriptor, and subsequent connection creation, data transfer, and so on are implemented through the socket.
There are two types of sockets that are commonly used: Streaming sockets (SOCK_STREAM) and datagram Sockets (SOCK_DGRAM). A stream is a connection-oriented socket that is applied to a connection-oriented TCP service; A datagram socket is a connectionless socket that corresponds to a connectionless UDP service application. Socket established to establish a socket, the program can call the socket function, which returns a handle similar to a file descriptor. The socket function prototype is: int socket (int domain, int type, int protocol);d Omain indicates the protocol family used, usually pf_inet, which means the Internet Protocol family (TCP/IP protocol family) The type parameter specifies the types of the socket: the Sock_stream or Sock_dgram,socket interface also defines the original socket (SOCK_RAW), allowing the program to use low-level protocols; Protocol is usually assigned "0". The socket () call returns an integral socket descriptor that you can use later in the call. The socket descriptor is a pointer to an internal data structure that points to the description chart entry. When you call the socket function, the socket executor creates a socket, in effect "building a socket" means allocating storage space for a socket data structure. The socket executor manages the descriptor table for you. A network connection between two network programs includes five types of information: communication Protocol, local protocol address, local host port, remote host address, and remote protocol port. The socket data structure contains these five kinds of information. Sockets are also widely used in measurement software.
Let's start with a simple example---a TCP service that receives an input string and processes and returns this string to the client. The following code is appropriate:

PHP Code:

--------------------------------------------------------------------------------

  1. ?
  2. Set some basic variables
  3. $host = "192.168.1.99";
  4. $port = 1234;
  5. Set timeout time
  6. Set_time_limit (0);
  7. Create a socket
  8. $socket = Socket_create (af_inet, sock_stream, 0) or die ("could not create
  9. Socket\n ");
  10. Bind socket to Port
  11. $result = Socket_bind ($socket, $host, $port) or die ("could not bind to"
  12. Socket\n ");
  13. Start listening for links
  14. $result = Socket_listen ($socket, 3) or die ("could not set up socket
  15. Listener\n ");
  16. Accept Incoming Connections
  17. Another socket to handle traffic
  18. $spawn = socket_accept ($socket) or die ("could not accept incoming
  19. Connection\n ");
  20. Get input from the client
  21. $input = Socket_read ($spawn, 1024) or die ("could not read input\n");
  22. Empty input string
  23. $input = Trim ($input);
  24. Process client input and return results
  25. $output = Strrev ($input). "\ n";
  26. Socket_write ($spawn, $output, strlen ($output)) or die ("could not write
  27. Output\n ");
  28. Close sockets
  29. Socket_close ($spawn);
  30. Socket_close ($socket);
  31. ?>
Copy Code



--------------------------------------------------------------------------------

The following is a detailed description of each of its steps:

1. The first step is to create two variables to hold the IP address and port of the server that the socket is running on. You can set your own server and port (this port can be a number from 1 to 65535), provided that the port is not in use.


PHP Code:

--------------------------------------------------------------------------------

    1. ?
    2. Set two variables
    3. $host = "192.168.1.99";
    4. $port = 1234;
    5. ?>
Copy Code




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.