我不能在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发布于 2017-05-17 16:18:27
在这里您如何设置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:", datahttps://stackoverflow.com/questions/44029765
复制相似问题