Python socketforbindelse mellem Windows og Linux

Indlæg af Hanne Mølgaard Plasc

Problem



Jeg kan ikke oprette en stikforbindelse mellem en Linux og en Windows-maskiner
Jeg ved ikke hvorfor klienten ikke accepterer forbindelsen, og serveren sidder bare der og venter på en klient, jeg ved ikke, hvad der er problemet
Jeg forsøgte at bruge forskellige måder at få vært på, men stadig et problem, denne kode ville arbejde fra et Linux-operativsystem til et Linux-OS, men ikke fra en Linux til Windows eller omvendt.


server kode:


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()


klientkode:


#!/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

Bedste reference


der hvordan du opsætter tcp:


serveren:


#!/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()


klienten :


#!/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