본문 바로가기

기타

[python] tcp 소켓 통신

반응형

python tcp 소켓 통신

code : https://github.com/madscheme/introducing-python

 

tcp_server.py 작성

from datetime import datetime
import socket

address = ('localhost', 6789)
max_size = 1000

print('Starting the server at', datetime.now())
print('Waiting for a client to call.')
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(address)
server.listen(5)

client, addr = server.accept()
data = client.recv(max_size)

print('At', datetime.now(), client, 'said', data)
client.sendall(b'Are you talking to me?')
client.close()
server.close()
A pair (host, port) is used for the AF_INET address family, where host is a string representing either a hostname in internet domain notation like 'daring.cwi.nl' or an IPv4 address like '100.50.200.5', and port is an integer.
- https://docs.python.org/3/library/socket.html

socket.SOCK_STREAM
socket.SOCK_DGRAM
These constants represent the socket types, used for the second argument to socket(). More constants may be available depending on the system. (Only SOCK_STREAM and SOCK_DGRAM appear to be generally useful.)
- https://docs.python.org/3/library/socket.html#socket.SOCK_DGRAM

 

tcp_client.py 작성

import socket
from datetime import datetime

address = ('localhost', 6789)
max_size = 1000

print('Starting the client at', datetime.now())
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(address)
client.sendall(b'Hey!')
data = client.recv(max_size)
print('At', datetime.now(), 'someone replied', data)
client.close()

python 프로그램 실행

터미널 #1

- tcp 서버 실행

$ python tcp_server.py
Starting the server at 2022-08-19 16:22:21.188050
Waiting for a client to call.

터미널 #2

- tcp 클라이언트 실행

$ python tcp_client.py
Starting the client at 2022-08-19 16:23:01.337282
At 2022-08-19 16:23:01.338904 someone replied b'Are you talking to me?'

터미널#1

- tcp 서버 로그 출력

At 2022-08-19 16:23:01.338813 <socket.socket fd=6, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=0, laddr=('127.0.0.1', 6789), raddr=('127.0.0.1', 54291)> said b'Hey!'

 

728x90
반응형