简体   繁体   中英

how to run a client and a server (w/ sockets) on python in mac?

i've build a very basic client

import socket
my_socket = socket.socket()
my_socket.connect(('127.0.0.1', 8820))
message = raw_input()
my_socket.send(message)
my_socket.close()

and a server

import socket

server_socket = socket.socket()
server_socket.bind(('0.0.0.0', 8820))

server_socket.listen(1)

(client_socket, client_address) = server_socket.accept()

client_name = client_socket.recv(1024)
client_socket.send('Hello ' + client_name + '!')

client_socket.close()
server_sockrt.close()

in windows i run them through cmd, how to run them on mac? thanks for help.

Hit Cmd-Space and enter term then hit Enter. This should open a Mac terminal window. By default the Python will be 2.7, which should work with your code.

Save the following file as server.py in your HOME directory:

#!/usr/bin/python
import socket

server_socket = socket.socket()
server_socket.bind(('0.0.0.0', 8820))

server_socket.listen(1)

(client_socket, client_address) = server_socket.accept()

client_data = client_socket.recv(1024)
print("Received: %s" % client_data)
client_socket.send('Hello ' + client_data + '!')

client_socket.close()
server_socket.close()

Save the following as client.py in your HOME directory:

#!/usr/bin/python
import socket
my_socket = socket.socket()
my_socket.connect(('127.0.0.1', 8820))
message = raw_input('Enter some data: ')
my_socket.send(message)
response_data = my_socket.recv(1024)
print("Received: %s" % response_data)
my_socket.close

Start Terminal , by hitting SPACE and typing "Terminal" followed by Enter .

Make both the scripts executable by running the following command once (it changes their mode by adding the x executable bit):

chmod +x *py

Now run the server with:

./server.py

Now press N , to get a New Terminal and in the new Terminal type:

./client.py

And everything should work.

The first line of each script is called a "shebang" in Unix if you want to learn about it.

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