簡単なTCP通信(python)

840 ワード

これは簡単なpython実装のtcp通信例である.
サーバ:
#!/usr/bin/python
import socket

#  socket
s = socket.socket()

# socket.gethostname()       IP
host = socket.gethostname()
port = 1234

s.bind((host, port))

# listen(n), n              
s.listen(5)

while True:
    # s.accept()     ,            
    c, addr = s.accept()

    print 'Got connection from', addr

    c.send('Thank you for connecting')

    c.close()
 
クライアント:
#!/usr/bin/python
import socket

s = socket.socket()

host = socket.gethostname()
port = 1234

s.connect((host, port))

print s.recv(1024)

 
それを出発点として拡張することができます.