python tcp

2018-01-02  本文已影响13人  极速魔法

python tcp

http://www.binarytides.com/python-socket-programming-tutorial/
https://www.jianshu.com/p/e062b3dd110c
https://www.liaoxuefeng.com

server.py

'''
open socket
bind (add,port)
listen for incoming connections
accept connections
receive/send

Accept a connection. The socket must be bound to an address and listening for connections.
The return value can be either None or a pair (conn, address)
where conn is a new socket object usable to send and receive data on the connection,
and address is the address bound to the socket on the other end of the connection.
'''
import socket
import sys
import threading
import time

host='127.0.0.1'
port=9999

s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
print('server socket created')

try:
    s.bind((host,port))
except socket.error:
    print('bind failed')
    sys.exit()
print('bind complete')

#listen
s.listen(10)
print('start listen...')


def tcplink(sock, addr):
    print('accept new connection {0}:{1}'.format(addr[0],str(addr[1])))
    #send message to connected client
    sock.send(b'welcome to server!')
    while True:
        #receive btye
        data=sock.recv(1024)
        msg='hello '+data.decode('utf-8')
        #time.sleep(1)
        if not data:
            break
        sock.sendall(msg.encode('utf-8'))
    sock.close()
    print('conection from {0}:{1} closed'.format(addr[0],addr[1]))

while True:
    #accept new connection
    sock,addr=s.accept()
    t=threading.Thread(target=tcplink,args=(sock,addr))
    t.start()

client.py

import socket
import sys

host='localhost'
port=9999

try:

    s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
except socket.error:
    print('socket create failed')
    sys.exit()

s.connect((host,port))
print(s.recv(1024).decode('utf-8'))

while True:
    data=input('please input some string\n')
    if not data or data=='exit':
        break

    s.sendall(str(data).encode('utf-8'))
    ret=s.recv(1024)
    print(ret.decode('utf-8'))
s.close()

上一篇 下一篇

猜你喜欢

热点阅读