Skip to content

Instantly share code, notes, and snippets.

@ssrlive
Last active March 29, 2018 14:55
Show Gist options
  • Save ssrlive/a942a4cb89a1cbeff31fa0fe948a739f to your computer and use it in GitHub Desktop.
Save ssrlive/a942a4cb89a1cbeff31fa0fe948a739f to your computer and use it in GitHub Desktop.
# -*- coding: utf-8 -*-
# https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/001432004374523e495f640612f4b08975398796939ec3c000#0
import socket, threading, time
#TCP socket based on ipv4
#server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#listening on port
s.bind(('0.0.0.0', 9999))
s.listen(5)
print("Waiting for connection...")
def tcplink(sock, addr):
print('Accept new connection from %s:%s...' % addr)
sock.send(b'Welcome!')
while True:
data = sock.recv(1024)
time.sleep(1)
if not data or data.decode('utf-8') == 'exit':
break
sock.send(('Hello, %s!' %data.decode('utf-8')).encode('utf-8'))
sock.close()
print('Connection from %s:%s closed.' % addr)
while True:
#receive a new connect
sock, addr = s.accept()
#make a new thread dispose TCPlink
t = threading.Thread(target=tcplink, args=(sock, addr))
t.start()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment