Socket Port Reuse

Source: Internet
Author: User

Write the socket program in Python and listen to the service on the specified port:

Import socket

Sock = Socket.socket (socket.af_inet, socket. SOCK_STREAM)
Port = 8080
Sock.bind (("', port)")
Sock.listen (1)
print ' Listening on port:%s '% port
While True:
Try
conn, addr = Sock.accept ()
print ' connected by%s:%s '% (addr[0], addr[1])
Except Keyboardinterrupt:
Break
Except Socket.error, msg:
print '%s '% msg

Provides a socket service on the port, terminates the program after the connection, and then runs the program again with an error message:
...
Socket.error: [Errno] Address already in use

You can resolve these issues by setting the socket reuse option SO_REUSEADDR, such as:

Import socket

Port = 8080
Server = Socket.socket (socket.af_inet, socket. SOCK_STREAM)
Server.setsockopt (socket. Sol_socket, SOCKET. SO_REUSEADDR, 1)
Server.bind (("', port)")
Server.listen (1)
print ' Listening on port:%s '% port
While True:
Try
conn, addr = Server.accept ()
print ' connected by%s:%s '% (addr[0], addr[1])
Except Keyboardinterrupt:
Break
Except Socket.error, msg:
print '%s '% msg

Tips:
Import socket

Sock = Socket.socket (socket.af_inet, socket. SOCK_STREAM)

state = sock.getsockopt (socket. Sol_socket, SOCKET. SO_REUSEADDR) # Get socket so_reuseaddr option status
print ' State state:%s '% State

Sock.setsockopt (socket. Sol_socket, SOCKET. SO_REUSEADDR, 1) #设置套接字选项
state = sock.getsockopt (socket. Sol_socket, SOCKET. SO_REUSEADDR)
print ' State state:%s '% State

Note: You can use the Telnet command to debug

www.pythonfan.org

Socket Port Reuse

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.