Python实现tcp服务端和客户端通信

原文:https://www.etdev.net/thread-60-1-1.html

 

1. 服务端Server

#!/usr/bin/env python3

# -*- coding: utf-8 -*-

 

import socket

import threading

import time

 

def tcp_thread(sock,addr):

print('new connection from %s,%s'%addr)

log('new connection from %s,%s'%addr)

sock.send(b'welcome')

try:

while True:

#receiving up to 1k bytes at a time

data=sock.recv(1024)

if not data or data.decode('utf-8')=='exit':

break

sock.send(data)

print(data.decode('utf-8'))

(ip,port)=addr

log('%s:%s %s'%(ip,port,data.decode('utf-8')))

 

sock.close()

except Exception as err:

print(err)

finally:

sock.close()

 

def start_tcp_server(ip,port):

#create socket

server=socket.socket(socket.AF_INET,socket.SOCK_STREAM)

#bind port

addr=(ip,port)

server.bind(addr)

#starting listening,allow 10 connection

try:

print ("starting listen on ip %s, port %s"%addr)

server.listen(10)

except socket.err as e:

print ("fail to listen on port %s"%e)

sys.exit(1)

#accept client connect

while True:

print ("\r\nwaiting for client connection")

client,addr=server.accept()

#create a thread to handle tcp link

thread=threading.Thread(target=tcp_thread,args=(client,addr))

thread.start()

def log(msg):

tm=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())

#writes the data to file

with open('server-debug.log','a') as f:

f.write('[%s] %s\r\n'%(tm,msg))

 

if __name__ == '__main__':

host=socket.gethostname()

ip=socket.gethostbyname(host)

start_tcp_server(ip,6800)

#start_tcp_server('0.0.0.0',6800)

 

2. 客户端Client

#!/usr/bin/env python3

# -*- coding: utf-8 -*-

 

import socket

import datetime

 

#create socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

 

host=socket.gethostname()

ip=socket.gethostbyname(host)

 

#connect to server

local=False

if local:

s.connect((ip,6800))

else:

s.connect(('47.98.163.223',6800))

 

#send test data

#s.send(b'tcp test')

 

#receive data

buf = []

while True:

#receiving up to 1k bytes at a time

d = s.recv(1024)

if d:

buf.append(d)

#print(buf)

print(d)

 

msg = input('please input data\r\n>>')

s.send(msg.encode('utf-8'))

#break

else:

break

 

s.close()

 

data = b''.join(buf)

 

print(data)

 

#writes the data to file

tm=datetime.datetime.now()

with open('client-debug.log','a') as f:

f.write('[%s] %s\r\n'%(tm,data))

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值