Python entry socket implementation UDP chat room

Source: Internet
Author: User

What is a Socket?

A socket is also called a socket, and an application usually makes a request to the network through a "socket" or responds to a network request, making it possible to communicate between hosts or between processes on a computer.

Socket () function

In Python, we use the socket () function to create a socket with the following syntax:

Socket.  Socket([family[, type[, Proto]])        
Parameters
    • Family: The socket family can make Af_unix or af_inet
    • Type: The socket type can be divided into either a connection-oriented or a non-connected SOCK_STREAMSOCK_DGRAM
    • Protocol: General does not fill the default is 0.
Socket object (built-in) method
function Description
Server-side sockets
S.bind () The binding address (Host,port) to the socket, under Af_inet, represents the address in the form of a tuple (host,port).
S.listen () Start TCP snooping. The backlog specifies the maximum number of connections that the operating system can suspend before rejecting the connection. This value is at least 1, and most applications are set to 5.
S.accept () Passively accepts TCP client connections, (blocking) waits for a connection to arrive
Client sockets
S.connect () Actively initializing the TCP server connection. The format of the general address is a tuple (hostname,port) and returns a socket.error error if there is an error in the connection.
S.CONNECT_EX () Extended version of the Connect () function, which returns an error code instead of throwing an exception when an error occurs
Socket functions for public use
S.RECV () Receives TCP data, the data is returned as a string, and bufsize specifies the maximum amount of data to receive. Flag provides additional information about the message, which can usually be ignored.
S.send () Sends the TCP data to the connected socket by sending the data in the string. The return value is the number of bytes to send, which may be less than the byte size of the string.
S.sendall () Complete sending of TCP data, complete sending of TCP data. Sends data from a string to a connected socket, but attempts to send all data before returning. Successful return none, Failure throws an exception.
S.recvfrom () The UDP data is received, similar to recv (), but the return value is (data,address). Where data is the string that contains the received information, address is the socket addressing that sent the data.
S.sendto () Sends UDP data, sends the data to the socket, address is a tuple in the form of (Ipaddr,port), specifies the remote address. The return value is the number of bytes sent.
S.close () Close socket
S.getpeername () Returns the remote address of the connection socket. The return value is typically a tuple (ipaddr,port).
S.getsockname () Returns the socket's own address. Typically a tuple (ipaddr,port)
S.setsockopt (Level,optname,value) Sets the value of the given socket option.
S.getsockopt (Level,optname[.buflen]) Returns the value of the socket option.
S.settimeout (Timeout) Sets the timeout period for the socket operation, and timeout is a floating-point number in seconds. A value of None indicates no over-time. In general, hyper-times should be set when a socket is just created, as they may be used for connected operations (such as Connect ())
S.gettimeout () Returns the value of the current timeout, in seconds, or none if the timeout period is not set.
S.fileno () Returns the file descriptor for the socket.
S.setblocking (flag) If flag is 0, the socket is set to nonblocking mode, otherwise the socket is set to blocking mode (the default value). In nonblocking mode, if the call recv () does not find any data, or the Send () call cannot send the data immediately, the Socket.error exception is raised.
S.makefile () Create a file associated with the socket

Implementing a UDP Chat room:

Required Module Socket threading

Idea: We need to use the socket module to receive data and send data, because we need to receive and send the function at the same time, so we need to use threading to create multithreading to achieve.

Send: Use the while True loop to enable s.sendto () to continuously send data to the remote side

Receive: The UDP data obtained by cyclic S.recvfrom () is printed to the console for real-time reception of data

Use threading to create incoming and outgoing threads, respectively.

#注 socket can only send data of byte type, so when sending the data to the byte type by Str.encode (), the receiver is converted to a string by Str.decode ().

Demo:


1 ImportSocket2 ImportThreading3 4 #input5host=Socket.gethostname ()6Port=int (Input ('Local Port:'))7Cliip=input ('Destination Address:')8Cliport=int (Input ('Destination Port:'))9Cliaddr=(Cliip,cliport)Ten Print('try and Target address'+str (CLIADDR) +'connection \ n') One A - - #Create socket thes=Socket.socket (Socket.af_inet,socket. SOCK_DGRAM) - S.bind ((host,port)) - - + #Accept - classServer (threading. Thread): + def __init__(self): AThreading. Thread.__init__(self) atself.host=Host -self.port=Port - defRun (self): - Print('open service side \ r \ n') - whileTrue: - inMsg,addr=s.recvfrom (2048)#Receive - Print('\ nthe receive from'+str (addr) +'Information: \n\t'+msg.decode () +'\ n:') to + - the #Send * classClient (threading. Thread): $ def __init__(self,cliip,cliport):Panax NotoginsengThreading. Thread.__init__(self) -self.cliip=CLIIP theself.cliport=Cliport + defRun (self): A whileTrue: theDate=input (':') +S.sendto (Date.encode (), cliaddr)#Send - $ $ - #Start Thread -thread1=Server () theThread2=Client (Cliip,cliport) - Thread1.start ()WuyiThread2.start ()

Python entry socket implementation UDP chat room

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.