Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sockets/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
同一python脚本中的套接字服务器和客户端_Python_Sockets - Fatal编程技术网

同一python脚本中的套接字服务器和客户端

同一python脚本中的套接字服务器和客户端,python,sockets,Python,Sockets,当我将套接字服务器和客户端代码保存在同一个脚本文件中时,下面的代码不起作用,我使用start\u new\u thread在主线程中运行服务器,在单独的线程中运行客户端 import socket, sys from thread import * host = socket.gethostname() s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: s.bind((host, 8888)) except socke

当我将套接字服务器和客户端代码保存在同一个脚本文件中时,下面的代码不起作用,我使用start\u new\u thread在主线程中运行服务器,在单独的线程中运行客户端

import socket, sys
from thread import *

host = socket.gethostname()
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
    s.bind((host, 8888))
except socket.error as msg:
    print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
    sys.exit()
s.listen(10)

def clientthread(conn):
    conn.send('Welcome to the server. Type something and hit enter\n')
    while True:
        data = conn.recv(1024)
        reply = 'OK...' + data
        if not data:
            break
        conn.sendall(reply)
    conn.close()

while 1:
    conn, addr = s.accept()
    print 'Connected with ' + addr[0] + ':' + str(addr[1])
    start_new_thread(clientthread ,(conn,))
s.close()
如果将
bind()
绑定到
gethostname()
,则还必须从客户端连接到该接口,即使该接口位于同一台计算机上<代码>“localhost”或
“127.0.0.1”
将不起作用。如果您想让它们工作,可以直接将
bind()
绑定到它们,或者绑定到所有内容(
“0.0.0.0”
,或者只绑定一个空字符串,

低预算测试代码:

from _thread import *
import socket,time

def client():
    print("Thread starts")
    time.sleep(1)
    print("Thread connects")
    sock=socket.create_connection((socket.gethostname(),8888))
    #sock=socket.create_connection(("localhost",8888))
    print("Thread after connect")
    sock.sendall(b"Hello from client")
    sock.close()
    print("Thread ends")

serv=socket.socket()
serv.bind((socket.gethostname(),8888))
#serv.bind(("localhost",8888))
#serv.bind(("0.0.0.0",8888))
#serv.bind(("",8888))
serv.listen(10)
start_new_thread(client,())
print("Before accept")
s,c=serv.accept()
print("After accept "+c[0])
print("Message: "+s.recv(1024).decode("ASCII"))
s.close()
serv.close()

请随意尝试测试各种sock+bind组合。

是否有错误消息?。。。顺便说一下,您不能将同一客户机两次连接到同一服务器。这将导致套接字错误。AFAIK,此代码执行要求它执行的操作:侦听端口8888,接受传入的连接,并启动一个新线程来回送该连接上的数据。你有什么问题?没有更多细节,这个问题就离题了。