简体   繁体   中英

Python socket connection between Windows and Linux

I can't set up a socket connection between a Linux and a windows machines I don't know why is the client not accepting the connection and the server is just sitting there waiting for a client i don't know what's the problem i tried using different ways to get the host but still a problem this code would work from a Linux OS to a Linux OS but not from a Linux to Windows or vice versa.

server code:

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

client code:

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

there how you setup tcp :

the server :

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

the client :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM