python socket编程
服务端
#!/usr/bin/env python
# coding=utf-8
from socket import *
HOST = ''
PORT = 2345
BUFSIZE = 1024
ADDR = (HOST,PORT)
#创建AF_INET地址族,TCP的套接字
with socket(AF_INET,SOCK_STREAM) as tcpSerSock:
#绑定ip和端口
tcpSerSock.bind(ADDR)
#监听端口,是否有请求
tcpSerSock.listen(5)
while True:
print("waiting for connect!!")
#accept() 是阻塞的
tcpClientSock,addr = tcpSerSock.accept()
print("the client: ",addr,"is connecting")
with tcpClientSock:
#使用一个while循环,持续和客户端通信,直到客户端断开连接或者崩溃
while True:
data = tcpClientSock.recv(BUFSIZE)
#判断客户端是否断开连接
if not data:
break;
print("client: ",data.decode("utf-8"))
#相应客户端请求
msg = input("server: ")
tcpClientSock.sendall(msg.encode("utf-8"))
#客户端退出
print("client ",addr,"exit!")
#!/usr/bin/env python
#