python client and server

诸葛文博
2023-12-01

client段代码如下:

import sys
from socket import *
serverHost = 'localhost'
serverPort = 1002

message = [b'Hello network world']
if len(sys.argv)> 1:
    serverHost =sys.argv[1]
    if len(sys.argv) >2:
        message = (x.encode() for x in sys.argv[2:])
    sockobj = socket(AF_INET , SOCK_STREAM)
    sockobj.connect((serverHost , serverPort))

    for line in message:
        sockobj.send(line)
        data = sockobj.recv(1024)
        print "client received:" , data

    sockobj.close()

放到client端机器上,运行的时候输入  python client  localhost abcdefg ,其中abcdefg是发送的信息。


from socket import *
myHost = ''
myPort = 1002

sockobj = socket(AF_INET , SOCK_STREAM)
sockobj.bind((myHost , myPort))
sockobj.listen(5)

while True:
    connection , address = sockobj.accept()
    print "Server connected by"  , address
    while True:
        data = connection.recv(1024)
        print "*"*30
        print data
        if not data:break
        connection.send(b'Echo=>'+data)
    connection.close()


运行server端程序,python server ,server端只负责接收,当接收完毕之后发送一个Echo=>abcdefg给客户端,表示接收完毕。

这段代码就这么简单,就完成了两个计算机基于TCP/IP的通讯。



参考资料:

http://www.cnblogs.com/vamei/archive/2012/10/30/2744955.html

http://www.lpfrx.com/archives/133/

 类似资料:

相关阅读

相关文章

相关问答