python tcp

python tcp

http://www.binarytides.com/python-socket-programming-tutorial/
http://www.itdecent.cn/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()

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Socket Socket是網(wǎng)絡(luò)編程的一個(gè)抽象概念。通常我們用一個(gè)Socket表示“打開了一個(gè)網(wǎng)絡(luò)鏈接”,而打開一...
    玩阿軻睡妲己閱讀 1,051評(píng)論 0 3
  • TCP編程 在python中可以使用socket模塊進(jìn)行TCP編程 客戶端 創(chuàng)建一個(gè)套接字socket 指定協(xié)議類...
    放風(fēng)箏的小小馬閱讀 365評(píng)論 0 1
  • 奧爾濱ALBION獨(dú)創(chuàng)的滲透乳的美容理論,真正實(shí)現(xiàn)了具有“透明感和柔韌性”的肌膚,從最初的5種產(chǎn)品發(fā)展到現(xiàn)在100...
    懋海閱讀 211評(píng)論 0 0
  • 國(guó)慶的時(shí)候和男朋有說了分手 同時(shí)在微博又更新了一篇關(guān)于你的微博 如果不是家庭問題的懸殊 我會(huì)選擇毫不猶豫的追求你 ...
    8dbfd81d8788閱讀 171評(píng)論 0 0
  • 昨天原本計(jì)劃開車回金昌的也因?yàn)閮鹤拥目咕芘轀恕R徽煳业那榫w都很低落、而我也沒有心情胃口吃飯、所以、也懲...
    梅燕霓閱讀 221評(píng)論 0 3

友情鏈接更多精彩內(nèi)容