Last active
September 23, 2016 15:15
-
-
Save tokibito/f0650b4608e06de70f611ffd8c5cbce0 to your computer and use it in GitHub Desktop.
PythonのsocketモジュールでHello, world!
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
socketモジュールを使ってHello, World | |
""" | |
import socket | |
bind_address = '127.0.0.1' | |
bind_port = 7777 | |
def main(): | |
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM,) | |
print("Start connect {}:{}".format(bind_address, bind_port)) | |
sock.connect((bind_address, bind_port)) | |
received = sock.recv(1024) | |
print(received.decode('utf8')) | |
sock.send(b"My name is Spam!") | |
sock.close() | |
if __name__ == '__main__': | |
main() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
socketモジュールを使ってHello, World | |
""" | |
import socket | |
import os | |
bind_address = '127.0.0.1' | |
bind_port = 7777 | |
def main(): | |
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) | |
sock.bind((bind_address, bind_port)) | |
sock.listen(1) | |
# os.fork() # 待ち受けるプロセスを増やす場合はここでforkすればいい | |
print("Start listen {}:{}".format(bind_address, bind_port)) | |
while True: | |
conn, (address, client_port) = sock.accept() | |
print("Connect from: {}, {}".format(address, client_port)) | |
conn.send(b"Hello, World!") | |
message = conn.recv(1024) | |
try: | |
print("[{}] {}".format(client_port, message.decode('utf8'))) | |
conn.close() | |
except Exception: | |
pass | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment