TCP客户端
import socket
def main():
#1、创建tcp套接字
tcp_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
#2、连接服务器
server_ip = "192.168.1.1"
server_port = 21990
tcp_socket.connect((server_ip,server_port))
#3、收发数据
send_data = ""
tcp_socket.send(send_data.encode("utf-8"))
#4、关闭套接字
tcp_socket.close()
if __name__ == '__main__':
main()
TCP服务器
import socket
def main():
#1、创建socket
tcp_server_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
#2、绑定
tcp_server_socket.bind(("10.1.0.245",53780))
#3、设置监听状态
tcp_server_socket.listen(128)
while True:
print("wait client...")
# 4、等待连接 有一个返回值 是一个元祖 两个参数值 拆包 一个新的套接字和客户地址
new_client_socket, client_addr = tcp_server_socket.accept()
print("get client...")
while True:
rev_data = new_client_socket.recv(1024)
print("client say:%s" % rev_data.decode('utf-8'))
#果然rev_data为空表示断开了
if rev_data:
new_client_socket.send("go".encode('utf-8'))
else:
break
new_client_socket.send("accept".encode('utf-8'))
new_client_socket.close()
tcp_server_socket.close()
if __name__ == '__main__':
main()
网友评论