Python-socket模拟TCP通讯

2019-10-17  本文已影响0人  木语沉心

Python socket模拟TCP通讯

本文将介绍使用Python的socket模块创建TCP客户端和服务端的方法。详细的模块介绍参见Python官方文档

对于TCP server端的创建而言,分为如下几个步骤:

示例代码如下:

Python socket: TCP server

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

|

其中,服务器地址二元组中,第一个元素为服务器IP(留空为在任意IP监听),第二个元素为服务器端口号。

而对于TCP client而言,通常包括如下几个步骤:

示例代码如下:

Python socket: TCP client


# /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"

    print  'Sending "%s".'  %  message

    sock.sendall(message)

    print  'Closing socket.'

    sock.close()

if  __name__  ==  "__main__":

    print  check_tcp_status("127.0.0.1",  12345)
上一篇 下一篇

猜你喜欢

热点阅读