对于tcp server 端的创建而言, 分为如下步骤:
1,创建socket对象(socket):其中俩个参数分别为
Address Family(如AF_INET为ipv4),AF_INET6为ipv6,AF_UNIX为unix域协议簇).
socket类型(如SOCK_STREAM为tcp,SOCK_DGRAM为udp)
2,绑定服务器地址(bind) : 参数为服务器地址二元组 也就是套接字
3,监听(listen): 参数为允许的连接数
4,等待请求(accpet): 建立一个连接,等待客户端
5,接收数据(recv,recvfrom ,recvfrom_into ,recv_into)
6,发送数据(send ,senfall ,sendto)
7,关闭连接(close)
代码:
#! /usr/bin/python # -*- coding: utf-8 -*- import socket sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM) server_address = ("127.0.0.1",12345) print "Staring up on %s:%s" % server_address sock.bind(server_address) sock.listen(5) while True: print "waiting .........." connetion,client_address = sock.accept() try: print "Connection from ",client_address data = connetion.recv(1024) print "Receive ‘%s‘" % data finally: connetion.close()
对于tcp client端而言 , 分为以下几个步骤:
1,创建socket对象( socket) : 同server端
2,连接服务器(connect) : 参数为服务器地址二元组
3,发送和接收数据: 同server端
4,关闭连接 : 同server端
代码:
#! /usr/bin/python # -*- coding: utf-8 -*- import socket sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM) def check_tcp_status(ip,port): sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM) server_address = (ip,port) print "connecting to %s:%s" % server_address,port sock.connect(server_address) message = raw_input("pleas input: ") print "Sending ‘%s‘" % message sock.sendall(message) print "Closing socket" sock.close() if __name__ == "__main__": print check_tcp_status("127.0.0.1",12345)
时间: 2024-10-13 06:21:39