📃
Python Reference
  • Installation
  • First Steps
  • Variables
  • Operators and Expressions
  • Control Flow
  • Loops
  • Functions
  • String
  • List
  • Dictionany
  • Modules
  • Class
  • File
  • Folder
  • Module os
  • Image
  • JSON
  • XML
  • Connection MySQL
  • Connection Redis
  • Connection Memcached
  • Connection RabbitMQ
  • Restful client
  • STMP
  • Socket
Powered by GitBook
On this page
  • Sever side
  • Client side
  • Follower me

Was this helpful?

Socket

Ở đây mình sẽ ví dụ việc xây dựng một môi trường Client - Server sử dụng Socket. Server sẽ lắng nghe trên một port (12345) và khi client kết nối vào sẽ thông báo hiển thị thông tin của client (IP và Port) và gởi 1 message xuống cho client.

Sever side

Tạo file server.py với nội dung bên dưới.

import socket

s = socket.socket()
host = socket.gethostname()
port = 12345
s.bind((host, port))

s.listen(5)
while True:
    c, addr = s.accept()
    print 'Got connection from', addr
    c.send('Thank you for connecting')
    c.close()

Đoạn code trên khi thực thi sẽ chạy và lắng nghe ở port TCP 12345. Mỗi khi có một kết nối từ client sẽ hiện ra thông báo kết nối từ IP và Port nào, Ví dụ: Got connection from Got connection from ('192.168.1.104', 60018) . Sau đó, gởi trả một message với nội dung Thank you for connecting về cho client. Sau đó, đóng kết nối với client.

Client side

Tạo file client.py với nội dung bên dưới.

import socket

s = socket.socket()
host = '127.0.0.1'
port = 12345

s.connect((host, port))
print s.recv(1024)
s.close

Đoạn code trên sẽ kết nối đến một socket server thông qua hostname lấy được từ phương thức socket.gethostname() và port 12345. Sau khi kết nối, sẽ hiển thị ra kết quả trả về từ server. Sau đó thì đóng kết nối.

Follower me

PreviousSTMP

Last updated 4 years ago

Was this helpful?

Facebook:

Blog:

Github:

https://www.facebook.com/lamsaodecode
https://lamsaodecode.blogspot.com
https://lamsaodecode.github.io/introduction