blog新地址 Surprised => indulgence => Calm => Lost => Panic =>Calm

Python套接字编程

Python admin 1876℃ 0评论

服务器端:

#!/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)

发送消息客户端 && 接收消息服务器

服务器

客户端

 

 

转载请注明:Imekaku-Blog » Python套接字编程

喜欢 (0)or分享 (0)
发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址