SOCKET基础编程
功能说明
- python版本3.5.1
- 客户端连接服务器,server发送欢迎词并询问用户姓名,收到client回复,向client发送‘hello,
***
’ - client向server发送数据,server打印收到的数据
- 用线程处理多客户端连接
Client
import socket
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(('localhost', 8080))
print(client.recv(1024).decode('utf-8'))
while True:
sendbuf = input()
client.send(sendbuf.encode('utf-8'))
if not sendbuf or sendbuf == 'exit':
break
recvbuf = client.recv(1024)
print(recvbuf.decode('utf-8'))
client.close()
print('Connection was closed...')
客户端运行截图
![这里写图片描述](https://img-blog.csdn.net/20170404222758496?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvamVycnloYW5qag==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)
Server
import socket
import threading
import time
ser = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ser.bind(('127.0.0.1', 8080))
ser.listen(5)
print('Server is running...')
def tcplink(connect, addr):
print('Accept new connection from %s:%s...' % addr)
connect.send(b'Welcome!\r\n'+b'Please tell me your name:')
data = connect.recv(1024)
connect.send(('Hello, %s' % data.decode('utf-8')).encode('utf-8'))
while True:
data = connect.recv(1024)
time.sleep(1)
if not data or data.decode('utf-8') == 'exit':
break
print("Device: %s, Data: %s, Size: %s" % (addr[0], data.decode('utf-8'), len(data)))
connect.send(b'Data Receive')
connect.close()
print('Connection from %s:%s closed' % addr)
while True:
sock, addr = ser.accept()
pthread = threading.Thread(target=tcplink, args=(sock, addr))
pthread.start()
服务器运行截图
![这里写图片描述](https://img-blog.csdn.net/20170404222704822?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvamVycnloYW5qag==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)