python 点对点语音_Python点对点聊天(Sockets)

我的任务是创建一个点对点的聊天应用程序,但是我在实际发送消息时遇到了问题。

实际上,应该提示用户输入他们想要连接的人的IP和端口,然后连续发送/接收消息。

但是,似乎在运行程序后立即建立了“随机”连接。

错误:Please enter the address you would like to connect on: 127.0.0.1

Please enter the port you would like to connect on: 5000

You: Established connection with: ('127.0.0.1', 2811)

为什么端口2811上有连接?这几乎就像程序正在连接到它自己。

代码:import socket

import threading

LOCALHOST = '127.0.0.1'

BUFFER_SIZE = 1024

def main():

class ChatListener(threading.Thread):

def __init__(self):

threading.Thread.__init__(self)

self.port = None

def run(self):

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

listen_socket.bind((LOCALHOST, self.port))

listen_socket.listen(1)

while True:

connection, address = listen_socket.accept()

print("Established connection with: ", address)

message = connection.recv(BUFFER_SIZE)

print("Them: ", message)

class ChatSender(threading.Thread):

def __init__(self):

threading.Thread.__init__(self)

self.address = None

self.port = None

def run(self):

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

send_socket.connect((self.address, self.port))

while True:

message = input("You: ")

if message.lower() == "quit":

break

else:

try:

send_socket.sendall(message)

except:

Exception

ip = input("Please enter the address you would like to connect on: ")

port = int(input("Please enter the port you would like to connect on: "))

chat_listener = ChatListener()

chat_listener.port = port

chat_listener.start()

chat_sender = ChatSender()

chat_sender.address = ip

chat_sender.port = port

chat_sender.start()

if __name__ == "__main__":

main()

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值