python--DenyHttp项目--socket编程:客户端与服务器端

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python--DenyHttp项目--socket编程:客户端与服务器端相关的知识,希望对你有一定的参考价值。

查找了许多资料,实现了客户端与服务器端的连接,通过虚拟机进行测试

服务器端IP:192.168.37.129 端口1122

客户端IP:  192.168.37.1 端口1122

Server:

#coding:utf-8
from socket import *
class Dserver():
    def __init__(self):
        self.HOST = ‘192.168.37.129‘
        self.PORT = 1122
        self.BUFSIZE = 1024
        self.ADDR = (self.HOST, self.PORT)
        self.sock = socket(AF_INET, SOCK_STREAM)
        
        self.sock.bind(self.ADDR)
    def listener(self):
        
        self.sock.listen(5)
        
        STOP_CHAT = False
        while not STOP_CHAT:
            print(‘等待接入,侦听端口:%d‘ % (self.PORT))
            topClientSock, addr = self.sock.accept()
            print(‘接受连接,客户端地址:‘,addr[0])
            while True:
                try:
                    data = topClientSock.recv(self.BUFSIZE)
                except:
                    topClientSock.close()
                    print("服务器关闭!")
                    break
                if not data:
                    print("数据为空")
                    break
                s=‘把服务器收到的从%s发送给我的信息:%s 发回来‘ %(addr[0],data.decode(‘utf-8‘))
                print(s)
                topClientSock.send(s.encode(‘utf-8‘))
                
                print(data.decode(‘utf-8‘))
                STOP_CHAT=(data.decode(‘utf-8‘).upper()=="QUIT")
                if STOP_CHAT:
                    break
                
        topClientSock.close()
        self.sock.close()
if __name__ == ‘__main__‘:
    serverDemo = Dserver()
    serverDemo.listener()
            
        

  Client:

#coding:utf-8
from socket import *
class Dclient():
    def __init__(self):
        self.HOST = ‘192.168.37.129‘
        self.PORT = 1122
        self.BUFSIZE = 1024
        self.ADDR = (self.HOST, self.PORT)
    def listener(self):
        self.client = socket(AF_INET,SOCK_STREAM)
        self.client.connect(self.ADDR)
        
        while True:
            data = input(‘>‘)
            if not data:
                break
            self.client.send(data.encode(‘utf-8‘))
            print(‘发送消息给%s: %s‘ % (self.HOST, data))
            if data.upper() == ‘QUIT‘:
                break
            data = self.client.recv(self.BUFSIZE)
            if not data:
                break
            print(‘接受的消息  %s‘ % (data.decode(‘utf-8‘)))

if __name__ == ‘__main__‘:
    clientDemo = Dclient()
    clientDemo.listener()
            

 

测试数据:

技术分享

技术分享

 

以上是关于python--DenyHttp项目--socket编程:客户端与服务器端的主要内容,如果未能解决你的问题,请参考以下文章

python--DenyHttp项目--ACM监考客户端测试版(1阶段完成总结)

python--DenyHttp项目--GUI:tkinter? module 'tkinter' has no attribute 'messagebox'

020 sock项目(单线程)

021 sock项目(多线程)

Linux端口转发到Socks代理

“.sock”不存在错误;连接()错误