Python下socket通信

Posted areful

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python下socket通信相关的知识,希望对你有一定的参考价值。

Server端代码:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: areful

# a server example which send hello to client.

import socket
import threading
import time


def tcp_link(_sock, _addr):
    print(\'Accept new connection from %s:%s...\' % _addr)
    _sock.send(bytes(\'Welcome!\', encoding=\'utf-8\'))
    while True:
        data = _sock.recv(1024)
        time.sleep(1)
        if data == \'exit\' or not data:
            break
        _sock.send(bytes(\'Hello, %s!\' % data, encoding=\'utf-8\'))
    _sock.close()
    print(\'Connection from %s:%s closed.\' % _addr)


s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((\'127.0.0.1\', 9999))
s.listen(5)
print(\'Waiting for connection...\')
while True:
    sock, addr = s.accept()
    t = threading.Thread(target=tcp_link, args=(sock, addr))
    t.start()

Client端代码:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: areful

\'a socket example which send echo message to server.\'

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((\'127.0.0.1\', 9999))
print(s.recv(1024))
for data in [\'Michael\', \'Tracy\', \'Sarah\']:
    s.send(bytes(data, encoding=\'utf-8\'))
    print(s.recv(1024))
s.send(bytes(\'exit\', encoding=\'utf-8\'))
s.close()

 

运行结果如图:  

 

以上是关于Python下socket通信的主要内容,如果未能解决你的问题,请参考以下文章

Python的网络编程socket

Socket通信关于Socket通信原理解析及python实现

Python socket通信~简单实例

Python网络编程-Socket简单通信

Python 中的代码,在 Node.js 和 Socket.IO 中通信,在 HTML 中呈现

Python 使用socket实现一对多通信