python tcp server 聊天工具

編程語言 Python 技術 巖姐姐 2017-04-25

今天在群裡看到 kami 在寫 tcp 和 udp 的 server 工具。然後我就科普一下資料,代碼算是搬的,也做了優化,因為學 python 學的不是太好,懶狗師傅給指出了錯誤。

在此感謝

服務端:

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

import socket

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

server_address = ('127.0.0.1', 12345)

print "Starting up on %s:%s" % server_address

sock.bind(server_address)

sock.listen(1)

while True:

print "Waiting for a connect"

connection, client_address = sock.accept()

try:

print "Connection from", client_address

data = connection.recv(1024)

print "Receive '%s'" % data

finally:

connection.close()

客戶端:

# coding: utf-8

import socket

def check_tcp_status(ip, port, b):

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

server_address = (ip, port)

print 'Connecting to %s:%s.' % server_address

sock.connect(server_address)

message = b

print 'Sending "%s".' % message

sock.sendall(message)

print 'Closing socket.'

if __name__ == "__main__":

a=raw_input('退出請輸入q任意鍵繼續')

s='q'

while a!=s:

b=raw_input("tell me")

check_tcp_status("127.0.0.1", 12345, b)

不要打擊我弱智的編程,關於使用的 “a”“b“”s”,請忽略。

截圖:

python tcp server 聊天工具

python tcp server 聊天工具

相關推薦

推薦中...