Client Programming:
The first thing to do is to create a socket, using the socket function in the socket template in Python.
Import socket
s = Socket.socket (socket.af_inet,socket. SOCK_STREAM)
There are two parameters behind the socket function:
Address Family: You can choose between af_inet (for Internet interprocess communication) or Af_unix (communication between the same machine)
Type: Socket type, either sock_stream (stream socket, primarily for TCP protocol) or SOCK_DGRAM (datagram socket, primarily for UDP protocol)
We know the server's IP address and port number, so I can connect using the Connect function.
S.connect (Ip,port)
After the connection is made, we can send the data to the server,
message = Data # is what you want to send
After sending it, we're going to accept the data.
Reply = S.recv (1024x768) #1024是一次可以接受的数据大小
Finally, we'll just connect the port to it.
S.close ()
The full code of the customer service is as follows:
1 #!usr/bin/env python2 #Coding:utf-83 4 ImportSocket5 6s =Socket.socket (Socket.af_inet,socket. SOCK_STREAM)7 Print 'Socket Created'8Host ='www.google.com'9Port = 80TenREMOTE_IP =Socket.gethostbyname (host) One #get the IP address of the host, gethostbyname is the IP address of the Web page you do not know, you can obtain a URL, generally on their own computer is not used A Printremote_ip - S.connect ((remote_ip,port)) -Message ='get/http/1.1\r\n\r\n' the #This is a command for HTTP request Web page content - s.sendall (message) - Print 'Message Send successfully' -Reply = S.recv (4096) + Printreply -S.close ()
Server and client are a little different
The main things the server does are:
1. Open the socket;
2. Bind to a specific address and port;
3. Monitor the connection;
4. Establish a connection;
5. Accept or send data
The specific code is as follows:
#!usr/bin/env python#Coding:utf-8ImportSockethost='127.0.0.1'PORT= 8888s=Socket.socket (Socket.af_inet,socket. Sock_stream) S.bind ((Host,port)) S.listen (5) whiletrue:conn,addr=s.accept () data= CONN.RECV (1024) Conn.sendall ('Welcome!') PrintDataifdata = ='Exit': If the accepted data =exit the loop when you exit Breakconn.close () s.close ( )
This is almost the case, and the rest is a matter of detail. I began to write a long time to write, according to other people's writing will always be wrong, the key is that others write but can run, heart plug!
The main references are:
Http://www.cnblogs.com/hazir/p/python_socket_programming.html
Python socket Programming (beginner)