python中一个简单的socket问题

2024-04-18 21:31:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我是网络编程领域的新手,所以我认为套接字是一个很好的起点。我做了一个简单的,但它总是返回一个错误。在

这就是错误

 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

发球

^{pr2}$

客户

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         

只有在我运行客户端之后,我才得到错误。在命令提示符下运行它也很重要吗


Tags: inpyimport网络hostport编程connect
3条回答

你要连接到哪个服务器?服务器需要在代码中有一个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()

客户:

^{pr2}$

下面是一个简单命令服务器的示例: 如果运行服务器代码,然后运行客户机,则可以键入客户机并发送到服务器。如果您键入TIME,您将从服务器获得一个response,其中包含一个字符串,该字符串的日期为今天,其他命令的工作方式相同。如果键入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

客户:

^{pr2}$

{1>主机不是本地的。请参阅运行server.py时打印的localhost地址。将主机变量更新到client.py中的该地址,这样可以解决问题。在

相关问题 更多 >