python中的一个简单套接字
我是网络编程领域的新手,所以我认为sockets是一个很好的起点。我做了一个简单的,但它不断抛出一个错误 这就是错误所在python中的一个简单套接字,python,python-2.7,sockets,Python,Python 2.7,Sockets,我是网络编程领域的新手,所以我认为sockets是一个很好的起点。我做了一个简单的,但它不断抛出一个错误 这就是错误所在 Traceback (most recent call last): File "/Users/mbp/Desktop/python user files/Untitled.py", line 3, in <module> client_socket.connect(('localhost', 5000)) File "/Library/Framew
Traceback (most recent call last):
File "/Users/mbp/Desktop/python user files/Untitled.py", line 3, in <module>
client_socket.connect(('localhost', 5000))
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/socket.py", line 228, in meth
return getattr(self._sock,name)(*args)
error: [Errno 61] Connection refused
客户
import socket
import os
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = '192.168.0.10'
port = 12345
s.connect((host, port))
print s.recv(1024)
s.close
只有在我运行客户端之后,我才会得到错误。在命令提示符下运行它也很重要,您要连接到哪个服务器?服务器需要在代码中有一个
server\u socket.accept()
,才能接受连接。从只看你的客户很难判断
为了帮助你,我将附加一个我用python编写的多客户端聊天,也许你可以从中学习一些python,它有线程和多客户端套接字连接,如果这对你来说太多了,我有一些更基本的东西,请发表评论让我知道
服务器:
import socket
import select
import thread
import random
from datetime import date
server_socket = socket.socket()
server_socket.bind(('0.0.0.0', 8820))
server_socket.listen(5)
open_client_sockets = []
open_client_sockets_with_name = []
message_to_send = []
new_name = "new"
# recives a client socket and finds it in the list of open client sockets and returns its name
def find_name_by_socket(current_socket):
for client_and_name in open_client_sockets_with_name:
(client_address, client_name) = client_and_name
if client_address == current_socket:
return client_name
# this function takes a commend, executes it and send the result to the client
def execute(cmd):
if cmd == "DATE":
current_socket.send(str(date.today()))
elif cmd == "NAME":
current_socket.send("best server ever")
elif cmd == "RAND":
current_socket.send(str(random.randrange(1,11,1)))
elif cmd == "EXIT":
current_socket.send("closing")
open_client_sockets.remove(current_socket)
open_client_sockets_with_name.remove((current_socket, find_name_by_socket(current_socket)))
current_socket.close()
else :
current_socket.send("there was an error in the commend sent")
def send_waiting_message(wlist):
# sends the message that needs to be sent
for message in message_to_send:
(client_socket, name, data) = message
if data[0] != '`':
print name + ": " + data
for client in wlist:
if client_socket != client:
client.send(name + ": " + data)
else: # this will execute a command and not print it
print "executing... " + data[1:]
execute(data[1:])
message_to_send.remove(message)
while True:
'''
rlist, sockets that you can read from
wlist, sockets that you can send to
xlist, sockets that send errors '''
rlist, wlist, xlist = select.select( [server_socket] + open_client_sockets,open_client_sockets , [] )
for current_socket in rlist:
if current_socket is server_socket:
(new_socket, address) = server_socket.accept()
new_name = new_socket.recv(1024)
print new_name + " connected"
open_client_sockets.append(new_socket)
open_client_sockets_with_name.append((new_socket, new_name))
else:
data = current_socket.recv(1024)
if data == "":
try:
open_client_sockets.remove(current_socket)
open_client_sockets_with_name.remove((current_socket, find_name_by_socket(current_socket)))
except:
print "error"
print "connection with client closed"
else:
message_to_send.append((current_socket, str(find_name_by_socket(current_socket)) , str(data)))
send_waiting_message(wlist)
server_socket.close()
客户:
import socket
import threading
global msg
# recives input from the server
def recv():
while True:
try: # try to recive that data the the server is sending
data = client_socket.recv(1024)
print data
except: # the connection is closed
return
# send user input to the server
def send():
while True: # store what the user wrote in the global variable msg and send it to the server
msg = raw_input("--- ")
client_socket.send(msg)
if msg == "`EXIT":
client_socket.close()
return
name = raw_input("enter your name ")
print "use ` to enter a commend"
try:
client_socket = socket.socket() # new socket
client_socket.connect(('127.0.0.1', 8820)) # connect to the server
client_socket.send(name) # send the name to the server
# since receving the server's output and sending the user's input uses blocking functions it is required to run them in a separate thread
thread_send = threading.Thread(target = send) # creates the thread in charge of sending user input
thread_recv = threading.Thread(target = recv) # creates the thread in charge of reciving server output
thread_recv.start() # starts the thread
thread_send.start() # starts the thread
except:
print "an error occurred in the main function"
client_socket.close()
import socket
client_socket = socket.socket() # new socket object
client_socket.connect(('127.0.0.1', 8820)) # connect to the server on port 8820, the ip '127.0.0.1' is special because it will always refer to your own computer
while True:
try:
print "please enter a commend"
print "TIME - request the current time"
print "NAME - request the name of the server"
print "RAND - request a random number"
print "EXIT - request to disconnect the sockets"
cmd = raw_input("please enter your name") # user input
client_socket.send(cmd) # send the string to the server
data = client_socket.recv(1024) # recive server output
print "the server sent: " + data # print that data from the server
print
if data == "closing":
break
except:
print "closing server"
break
client_socket.close() # close the connection with the server
您正在连接到哪个服务器?服务器需要在代码中有一个
server\u socket.accept()
,才能接受连接。从只看你的客户很难判断
为了帮助你,我将附加一个我用python编写的多客户端聊天,也许你可以从中学习一些python,它有线程和多客户端套接字连接,如果这对你来说太多了,我有一些更基本的东西,请发表评论让我知道
服务器:
import socket
import select
import thread
import random
from datetime import date
server_socket = socket.socket()
server_socket.bind(('0.0.0.0', 8820))
server_socket.listen(5)
open_client_sockets = []
open_client_sockets_with_name = []
message_to_send = []
new_name = "new"
# recives a client socket and finds it in the list of open client sockets and returns its name
def find_name_by_socket(current_socket):
for client_and_name in open_client_sockets_with_name:
(client_address, client_name) = client_and_name
if client_address == current_socket:
return client_name
# this function takes a commend, executes it and send the result to the client
def execute(cmd):
if cmd == "DATE":
current_socket.send(str(date.today()))
elif cmd == "NAME":
current_socket.send("best server ever")
elif cmd == "RAND":
current_socket.send(str(random.randrange(1,11,1)))
elif cmd == "EXIT":
current_socket.send("closing")
open_client_sockets.remove(current_socket)
open_client_sockets_with_name.remove((current_socket, find_name_by_socket(current_socket)))
current_socket.close()
else :
current_socket.send("there was an error in the commend sent")
def send_waiting_message(wlist):
# sends the message that needs to be sent
for message in message_to_send:
(client_socket, name, data) = message
if data[0] != '`':
print name + ": " + data
for client in wlist:
if client_socket != client:
client.send(name + ": " + data)
else: # this will execute a command and not print it
print "executing... " + data[1:]
execute(data[1:])
message_to_send.remove(message)
while True:
'''
rlist, sockets that you can read from
wlist, sockets that you can send to
xlist, sockets that send errors '''
rlist, wlist, xlist = select.select( [server_socket] + open_client_sockets,open_client_sockets , [] )
for current_socket in rlist:
if current_socket is server_socket:
(new_socket, address) = server_socket.accept()
new_name = new_socket.recv(1024)
print new_name + " connected"
open_client_sockets.append(new_socket)
open_client_sockets_with_name.append((new_socket, new_name))
else:
data = current_socket.recv(1024)
if data == "":
try:
open_client_sockets.remove(current_socket)
open_client_sockets_with_name.remove((current_socket, find_name_by_socket(current_socket)))
except:
print "error"
print "connection with client closed"
else:
message_to_send.append((current_socket, str(find_name_by_socket(current_socket)) , str(data)))
send_waiting_message(wlist)
server_socket.close()
客户:
import socket
import threading
global msg
# recives input from the server
def recv():
while True:
try: # try to recive that data the the server is sending
data = client_socket.recv(1024)
print data
except: # the connection is closed
return
# send user input to the server
def send():
while True: # store what the user wrote in the global variable msg and send it to the server
msg = raw_input("--- ")
client_socket.send(msg)
if msg == "`EXIT":
client_socket.close()
return
name = raw_input("enter your name ")
print "use ` to enter a commend"
try:
client_socket = socket.socket() # new socket
client_socket.connect(('127.0.0.1', 8820)) # connect to the server
client_socket.send(name) # send the name to the server
# since receving the server's output and sending the user's input uses blocking functions it is required to run them in a separate thread
thread_send = threading.Thread(target = send) # creates the thread in charge of sending user input
thread_recv = threading.Thread(target = recv) # creates the thread in charge of reciving server output
thread_recv.start() # starts the thread
thread_send.start() # starts the thread
except:
print "an error occurred in the main function"
client_socket.close()
import socket
client_socket = socket.socket() # new socket object
client_socket.connect(('127.0.0.1', 8820)) # connect to the server on port 8820, the ip '127.0.0.1' is special because it will always refer to your own computer
while True:
try:
print "please enter a commend"
print "TIME - request the current time"
print "NAME - request the name of the server"
print "RAND - request a random number"
print "EXIT - request to disconnect the sockets"
cmd = raw_input("please enter your name") # user input
client_socket.send(cmd) # send the string to the server
data = client_socket.recv(1024) # recive server output
print "the server sent: " + data # print that data from the server
print
if data == "closing":
break
except:
print "closing server"
break
client_socket.close() # close the connection with the server
您正在启动的服务器没有地址
192.168.0.10
,而是本地主机。请参阅运行server.py
时打印的localhost
地址。将主机变量更新到client.py
中的该地址,这将解决问题。您正在启动的服务器没有地址192.168.0.10
,而是本地主机。请参阅运行server.py
时打印的localhost
地址。将主机变量更新到client.py中的该地址,这将解决问题。下面是一个简单命令服务器的示例:
如果运行服务器代码,然后运行客户端,则可以键入客户端并发送到服务器。如果您键入TIME,您将从服务器获得一个respons,其中包含一个日期为今天的字符串,其他命令的工作方式与此相同。如果键入EXIT,它将关闭连接,并将从服务器向客户端发送关闭字符串
import socket
import os
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = '192.168.0.10'
port = 12345
s.connect((host, port))
print s.recv(1024)
s.close
服务器:
import socket
import random
from datetime import date
server_socket = socket.socket() # new socket object
server_socket.bind(('0.0.0.0', 8820)) # empty bind (will connect to a real ip later)
server_socket.listen(1) # see if any client is trying to connect
(client_socket, client_address) = server_socket.accept() # accept the connection
while True: # main server loop
client_cmd = client_socket.recv(1024) # recive user input from client
# check waht command was entered
if client_cmd == "TIME":
client_socket.send(str(date.today())) # send the date
elif client_cmd == "NAME":
client_socket.send("best server ever") # send this text
elif client_cmd == "RAND":
client_socket.send(str(random.randrange(1,11,1))) # send this randomly generated number
elif client_cmd == "EXIT":
client_socket.send("closing")
client_socket.close() # close the connection with the client
server_socket.close() # close the server
break
else :
client_socket.send("there was an error in the commend sent")
client_socket.close() # just in case try to close again
server_socket.close() # just in case try to close again
客户:
import socket
import threading
global msg
# recives input from the server
def recv():
while True:
try: # try to recive that data the the server is sending
data = client_socket.recv(1024)
print data
except: # the connection is closed
return
# send user input to the server
def send():
while True: # store what the user wrote in the global variable msg and send it to the server
msg = raw_input("--- ")
client_socket.send(msg)
if msg == "`EXIT":
client_socket.close()
return
name = raw_input("enter your name ")
print "use ` to enter a commend"
try:
client_socket = socket.socket() # new socket
client_socket.connect(('127.0.0.1', 8820)) # connect to the server
client_socket.send(name) # send the name to the server
# since receving the server's output and sending the user's input uses blocking functions it is required to run them in a separate thread
thread_send = threading.Thread(target = send) # creates the thread in charge of sending user input
thread_recv = threading.Thread(target = recv) # creates the thread in charge of reciving server output
thread_recv.start() # starts the thread
thread_send.start() # starts the thread
except:
print "an error occurred in the main function"
client_socket.close()
import socket
client_socket = socket.socket() # new socket object
client_socket.connect(('127.0.0.1', 8820)) # connect to the server on port 8820, the ip '127.0.0.1' is special because it will always refer to your own computer
while True:
try:
print "please enter a commend"
print "TIME - request the current time"
print "NAME - request the name of the server"
print "RAND - request a random number"
print "EXIT - request to disconnect the sockets"
cmd = raw_input("please enter your name") # user input
client_socket.send(cmd) # send the string to the server
data = client_socket.recv(1024) # recive server output
print "the server sent: " + data # print that data from the server
print
if data == "closing":
break
except:
print "closing server"
break
client_socket.close() # close the connection with the server
下面是一个简单命令服务器的示例:
如果运行服务器代码,然后运行客户端,则可以键入客户端并发送到服务器。如果您键入TIME,您将从服务器获得一个respons,其中包含一个日期为今天的字符串,其他命令的工作方式与此相同。如果键入EXIT,它将关闭连接,并将从服务器向客户端发送关闭字符串
import socket
import os
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = '192.168.0.10'
port = 12345
s.connect((host, port))
print s.recv(1024)
s.close
服务器:
import socket
import random
from datetime import date
server_socket = socket.socket() # new socket object
server_socket.bind(('0.0.0.0', 8820)) # empty bind (will connect to a real ip later)
server_socket.listen(1) # see if any client is trying to connect
(client_socket, client_address) = server_socket.accept() # accept the connection
while True: # main server loop
client_cmd = client_socket.recv(1024) # recive user input from client
# check waht command was entered
if client_cmd == "TIME":
client_socket.send(str(date.today())) # send the date
elif client_cmd == "NAME":
client_socket.send("best server ever") # send this text
elif client_cmd == "RAND":
client_socket.send(str(random.randrange(1,11,1))) # send this randomly generated number
elif client_cmd == "EXIT":
client_socket.send("closing")
client_socket.close() # close the connection with the client
server_socket.close() # close the server
break
else :
client_socket.send("there was an error in the commend sent")
client_socket.close() # just in case try to close again
server_socket.close() # just in case try to close again
客户:
import socket
import threading
global msg
# recives input from the server
def recv():
while True:
try: # try to recive that data the the server is sending
data = client_socket.recv(1024)
print data
except: # the connection is closed
return
# send user input to the server
def send():
while True: # store what the user wrote in the global variable msg and send it to the server
msg = raw_input("--- ")
client_socket.send(msg)
if msg == "`EXIT":
client_socket.close()
return
name = raw_input("enter your name ")
print "use ` to enter a commend"
try:
client_socket = socket.socket() # new socket
client_socket.connect(('127.0.0.1', 8820)) # connect to the server
client_socket.send(name) # send the name to the server
# since receving the server's output and sending the user's input uses blocking functions it is required to run them in a separate thread
thread_send = threading.Thread(target = send) # creates the thread in charge of sending user input
thread_recv = threading.Thread(target = recv) # creates the thread in charge of reciving server output
thread_recv.start() # starts the thread
thread_send.start() # starts the thread
except:
print "an error occurred in the main function"
client_socket.close()
import socket
client_socket = socket.socket() # new socket object
client_socket.connect(('127.0.0.1', 8820)) # connect to the server on port 8820, the ip '127.0.0.1' is special because it will always refer to your own computer
while True:
try:
print "please enter a commend"
print "TIME - request the current time"
print "NAME - request the name of the server"
print "RAND - request a random number"
print "EXIT - request to disconnect the sockets"
cmd = raw_input("please enter your name") # user input
client_socket.send(cmd) # send the string to the server
data = client_socket.recv(1024) # recive server output
print "the server sent: " + data # print that data from the server
print
if data == "closing":
break
except:
print "closing server"
break
client_socket.close() # close the connection with the server
谢谢,客户端和服务器是我的电脑,看起来它们是一样的。这不是我所要求的,客户端和服务器在你的电脑上运行,但它们是两个不同的代码页,因为客户端和服务器不可能写在同一个文件中,它们需要分开运行。我需要查看服务器的代码,以便帮助解决最初的问题现在我看到了,很抱歉我第一次读你的帖子时错过了它(愚蠢的阅读障碍)。我想你需要在你的第11行加上(),顺便说一句(c,addr)=s。accept()仍然抛出相同的错误。你能帮我一个忙吗?请发送一个简单的插座,只用于确认连接,我可以在上面玩。行了,我只是给它添加了更好的注释,这样你就可以理解了。谢谢,客户和服务是我的电脑,看起来它们是一样的。这不是我要求的,客户端和服务器在您的pc上运行,但它们是两个不同的代码页,因为客户端和服务器不可能写入同一个文件,它们需要分开并单独运行。我需要查看服务器的代码,以便帮助解决最初的问题现在我看到了,很抱歉我第一次读你的帖子时错过了它(愚蠢的阅读障碍)。我想你需要在你的第11行加上(),顺便说一句(c,addr)=s。accept()仍然抛出相同的错误。你能帮我一个忙,发送一个只用于确认连接的简单套接字,我可以从中使用它。行了,我只是给它添加了更好的注释,这样你就可以了解客户和服务在同一台机器上。我只想确认连接。客户端和服务器在同一台机器上。我只是想确认连接。@Mohamedurdan您能提供更多信息吗?我使用了从localhost获得的ip,并按照您的建议在客户端文件中使用了它,但仍然收到相同的错误message@mohamedurrdan它适用于我,除此之外没有任何变化。@Mohamedurdan你能提供更多信息吗?我使用了我从localhost并按照您的建议在客户机文件中使用了它,但仍然收到相同的错误message@mohamedurrdan它对我有效,除此之外没有任何变化。非常感谢。我应该使用终端还是按原样运行?你可以随意运行,但我建议下载PyCharm,然后你只需右键单击包含代码的文件,然后单击“运行”。确保在文件->设置->项目:“项目名称”->项目解释器中将解释器设置配置为2.7.x。我有PyCharm。现在一切都很有魅力。我现在更了解套接字了。幸好我在6个月前是python的乞丐,所以我知道掌握基本知识有多难。非常感谢。我应该使用终端还是按原样运行?你可以随意运行,但我建议下载PyCharm,然后你只需右键单击包含代码的文件,然后单击“运行”。确保在文件->设置->项目:“项目名称”->项目解释器中将解释器设置配置为2.7.x。我有PyCharm。每个人