Python之路——网络编程

socket

TCP

服务端

 1 import socket
 2 sk = socket.socket()
 3 sk.bind(('127.0.0.1',8080)) # 绑定ip和端口号
 4 sk.listen() # Enable a server to accept connections.
 5 conn,addr = sk.accept() # Wait for an incoming connection.  Return a new socket
 6                         # representing the connection, and the address of the client.
 7 while 1:
 8     content = conn.recv(1024)   # 接收
 9     print(content.decode('utf-8'))
10     conn.send(content+b'--liuyankui')   # 发送
11 conn.close()
12 sk.close()

客户端

1 import socket
2 sk = socket.socket()
3 sk.connect(('127.0.0.1',8080))  #连接
4 while 1:
5     content = input('>>>').encode('utf-8')
6     sk.send(content)
7     ret = sk.recv(1024)
8     print(ret.decode('utf-8'))
9 sk.close()

 

UDP

服务端

1 import socket
2 sk = socket.socket(type=socket.SOCK_DGRAM)
3 sk.bind(('127.0.0.1',8080))
4 msg ,addr = sk.recvfrom(1024)
5 print(msg.decode('utf-8'))
6 sk.sendto(b'bye',addr)
7 sk.close()

用户端

1 import socket
2 sk = socket.socket(type=socket.SOCK_DGRAM)
3 ip_port = ('127.0.0.1',8080)
4 sk.sendto(b'hello',ip_port)
5 msg,addr = sk.recvfrom(1024)
6 print(msg.decode('utf-8'))
7 sk.close()

 socketserver

server端

 1 import socketserver
 2 
 3 class MyServer(socketserver.BaseRequestHandler):
 4     def handle(self):
 5         while True:
 6             msg = self.request.recv(1024).decode('utf-8')
 7             if msg=='q':return
 8             print(msg)
 9             info = input('(sent to %s)>>>' %(msg[:2]))
10             self.request.send(info.encode('utf-8'))
11 if __name__ == '__main__':
12     server = socketserver.ThreadingTCPServer(('127.0.0.1',8080),MyServer)
13     server.serve_forever()

client端

 1 import socket
 2 sk = socket.socket()
 3 sk.connect(('127.0.0.1',8080))
 4 while 1:
 5     msg = input('>>>')
 6     if msg == 'q':
 7         sk.send('q'.encode('utf-8'))
 8         break
 9     sk.send(('美团外卖:'+msg).encode('utf-8'))
10     print(sk.recv(1024).decode('utf-8'))
11 sk.close()

 

posted @ 2018-01-29 11:17  liuyankui163  阅读(138)  评论(0编辑  收藏  举报