我是网络编程领域的新手,所以我认为套接字是一个很好的起点。我做了一个简单的但它不断抛出错误。
这是错误
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=socket.gethostbyname('localhost')
port=12345
s.bind((host,port))
s.listen(5)
print host
while True:
c, addr = s.accept()
print 'Got connection from', addr
c.send('Thank you for connecting')
c.close()
客户
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
仅在我运行客户端之后我才收到错误。在命令提示符
上运行它也很重要答案 0 :(得分:1)
你连接的服务器是什么?服务器需要在代码中有server_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()
答案 1 :(得分:1)
您启动的服务器没有地址192.168.0.10
,而是本地主机。查看运行localhost
时打印的server.py
地址。将主机变量更新为client.py
中的该地址,以解决问题。
答案 2 :(得分:0)
以下是一个简单命令服务器的示例: 如果您运行服务器代码然后运行客户端,您将能够键入客户端并发送到服务器。如果你键入TIME,你将从服务器获得一个响应,其中包含一个具有今天日期的字符串,其他命令以相同的方式工作。如果您输入EXIT,它将关闭连接,并将从服务器发送关闭到客户端的字符串
服务器:
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
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