gpt4 book ai didi

Windows和Linux之间的Python套接字连接

转载 作者:行者123 更新时间:2023-12-03 12:09:23 25 4
gpt4 key购买 nike

我无法在 Linux 和 Windows 机器之间建立套接字连接
我不知道为什么客户端不接受连接而服务器只是坐在那里等待客户端我不知道是什么问题
我尝试使用不同的方法来获取主机,但仍然存在问题,此代码可以从 Linux 操作系统运行到 Linux 操作系统,但不能从 Linux 运行到 Windows,反之亦然。

服务器代码:

import os #importing the os module

import socket #importing the socket module

store_folder = "socket_info7" # assigning the variable store_folder to the value "socket_info"

os.mkdir(store_folder) #using the variable value to make a folder named socket_info

os.chdir(store_folder) # changing the directory to socket_info

store_file = store_folder+" 1"

store_file = open(store_file,"a") # make a file named socket_info

s= socket.socket() # making a socket object

host = socket.gethostname()

port = 5000

s.bind((host,port))

s.listen(1)

while True:

c,addr = s.accept()

user_input = raw_input("write")

c.send(user_input)

if user_input == "q":

break

s.close()

客户端代码:
#!/usr/bin/python           # This is server.py file

import socket # Import socket module

s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = 5000 # Reserve a port for your service.
s.bind((host, port)) # Bind to the port

s.listen(5) # Now wait for client connection.
while True:
c, addr = s.accept() # Establish connection with client.
print 'Got connection from', addr
c.send('Thank you for connecting')
c.close() # Close the connection

最佳答案

那里你如何设置 tcp :

服务器 :

#!/usr/bin/env python

import socket


TCP_IP = '127.0.0.1'
TCP_PORT = 5005
BUFFER_SIZE = 20 # Normally 1024, but we want fast response

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((TCP_IP, TCP_PORT))
s.listen(1)

conn, addr = s.accept()
print 'Connection address:', addr
while 1:
data = conn.recv(BUFFER_SIZE)
if not data: break
print "received data:", data
conn.send(data) # echo
conn.close()

客户端 :
#!/usr/bin/env python

import socket


TCP_IP = '127.0.0.1'
TCP_PORT = 5005
BUFFER_SIZE = 1024
MESSAGE = "Hello, World!"

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))
s.send(MESSAGE)
data = s.recv(BUFFER_SIZE)
s.close()

print "received data:", data

关于Windows和Linux之间的Python套接字连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44029765/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com