【发布时间】:2015-09-13 20:09:13
【问题描述】:
嘿,我刚刚转发了我的端口和我的 Python 服务器 从另一台 PC 运行客户端时,客户端聊天按预期工作。
当我尝试从我自己的 PC(服务器文件本身所在的位置)连接客户端时,我得到了他的错误:
OSError: [WinError 10048] Only one usage of each socket address (protocol/network address/port) is normally permitted
Q1:这意味着只有 1 个应用可以连接到特定端口,对吧?
Q2:那么,如何在同一台 PC 上同时开发我的服务器和客户端? (我没有其他电脑可以做)
如果需要,这是我的代码。 (我刚开始,所以不要评判)
服务器:
from tkinter import *
#from mysql.connector import (connection)
import socket
from _thread import *
import sys
root = Tk()
T = Text(root, height=2, width=30)
T2 = Text(root, height=2, width=30)
B = Button(root, text="Send")
T.pack(side=LEFT,fill=X)
T2.pack(side=TOP,fill=X)
B.pack(side=LEFT,fill=X)
#statick ip
host = 'x.x.x.x'
port=yyyy
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.bind((host,port))
try:
s.bind((host,port))
except socket.error as e:
print(str(e))
s.listen(5)
print("waiting for connection")
def threaded_client(conn):
conn.send(str.encode("Connection with the server established\n"))
while True:
data = conn.recv(2048)
reply = "You: " + data.decode('utf-8')
if not data:
break
conn.sendall(str.encode(reply))
conn.close()
while True:
conn, addr = s.accept()
print('connected to: '+ addr[0]+':'+str(addr[1]))
start_new_thread(threaded_client,(conn,))
root.mainloop()
客户:
from tkinter import *
import socket
print("everything is imported")
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
print("socket is established")
#the public ip
host = 'y.y.y.y'
port=xxxx
s.connect((host,port))
print("s.connect done")
def sendShit(event):
textToSend = T.get("1.0",END)
s.send(str.encode(textToSend))
T2.insert(END, s.recv(1024))
print("sendshit defined")
root = Tk()
T = Text(root, height=2, width=30)
T2 = Text(root, height=2, width=30)
B = Button(root, text="Send")
T.pack(side=LEFT,fill=X)
T2.pack(side=TOP,fill=X)
B.pack(side=LEFT,fill=X)
T.insert(END, "Type here")
T2.insert(END, s.recv(1024))
B.bind("<Button-1>",sendShit)
mainloop()
【问题讨论】:
-
只需在两个文件上设置
host = '127.0.0.1'(这是您的localhost并将port设置为相同的数字(例如6000) -
我已经发布了答案...如果您认为它对您有帮助,请考虑接受它。谢谢
标签: python sockets client server