服务器端:
#!/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 "Starting up on %s:%s" % server_address sock.bind(server_address) sock.listen(1) while True: print "Waiting for a connection" connection, client_address = sock.accept() try: print "Connection from", client_address data = connection.recv(1024) print "Receive '%s'" % data finally: connection.close()
这里:sock.listen(1)
表示此套接字最多允许多少个客户连接到服务器。
它的值至少为1。收到连接请求后,这些请求需要排队,如果队列满,就拒绝请求。
客户端:
# /usr/bin/python # -*- coding: utf-8 -*- import socket 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 sock.connect(server_address) # message = "I'm TCP client" message = ['1',2,"Hi"] print 'Sending "%s".' % message sock.sendall(str(message)) print 'Closing socket.' sock.close() if __name__ == "__main__": print check_tcp_status("127.0.0.1", 12345)
发送消息客户端 && 接收消息服务器
服务器
#!/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 "Starting up on %s:%s" % server_address sock.bind(server_address) sock.listen(1) while True: connection, client_address = sock.accept() try: data = connection.recv(1024).strip("\n") print data finally: connection.close()
客户端
# /usr/bin/python # -*- coding: utf-8 -*- import socket import sys 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 sock.connect(server_address) while True: message = sys.stdin.readline() if message == "S": break print message.strip("\n") sock.sendall(str(message)) sock.close() if __name__ == "__main__": print check_tcp_status("127.0.0.1", 12345)