网络编程入门

来自廖雪峰的网络编程。

客户端需要主动发起connect,然后服务器端先设置监听的端口,然后发现connect后就新建一个线程处理。

socket_server.py

import socket
import threading
import time
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('127.0.0.1', 9999))
s.listen(5)
print('Waiting for connection..')


def tcplink(sock, addr):
	print(addr)
	print('in server Welcome')
	sock.send(b'server send to client: 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 closed %s:%s' % addr)


while True:
	sock, addr = s.accept()
	t = threading.Thread(target=tcplink, args=(sock, addr))
	t.start()
socket_client.py

import socket
import threading
import time

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('127.0.0.1', 9999))
print(s.recv(1024).decode('utf-8'))#此处接收的数据就是send发过来的welcome

for data in [b'mashijia', b'zhaolulu', b'huoxb']:
	s.send(data)
	print(s.recv(1024).decode('utf-8'))
s.send(b'exit')
s.close()



你可能感兴趣的:(网络编程入门)