首页 > 编程语言 > 详细

Python下socket通信

时间:2019-02-14 23:37:22      阅读:234      评论:0      收藏:0      [点我收藏+]

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通信

原文:https://www.cnblogs.com/areful/p/10381294.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!