python socket programming

markyang92·2021년 4월 23일
0

python

목록 보기
23/42

echo server-client

server

from http import server
import socket

if __name__ == '__main__':
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    print(server_socket)

    server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

    server_socket.bind(('127.0.0.1',48885))
    print(server_socket)

    server_socket.listen()

    client1_socket, addr = server_socket.accept()

    print(f'server socket: {server_socket}')
    print(f'client1 socket: {client1_socket}')

    # 접속한 클라이언트 주소
    print(f'Connected by : {addr}')

    while True:
        data = client1_socket.recv(1024)
        if not data:
            break
        print(f'Received from {addr}: {data.decode()}')

        client1_socket.sendall(data)

    client1_socket.close()
    server_socket.close()


client

#!/usr/bin/env python3

from http import client
import socket

if __name__ == '__main__':
    client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    print(client_socket)
    client_socket.connect(('127.0.0.1',48885))
    print(client_socket)

    client_socket.sendall('안녕'.encode())

    data = client_socket.recv(1024)
    print(f'Client Received: {repr(data.decode())}')


    client_socket.close()


thread server

server

thread

import _thread

def tFunc(str1, str2):
	
    cnt=1
    print(str1+' '+str2' {}'.format(cnt))
    cnt+=1
    
a="hello"
b="world"
_thread.start_new_thread(tFunc, (a,b))    # 반드시 2nd arg는 튜플!

client


간단한 web server

import argparse
import socket
import socketserver
import http.server

parser = argparse.ArgumentParser(description="Simple web viewer")
parser.add_argument('-t', '--target', action='store', required=True,
                        type=str, metavar='user@device-ip')
parser.add_argument('-s', '--target-port', action='store',
                        default=22, type=int, metavar='N',
                        help='Specify alternate target ssh port [default: 22]')
parser.add_argument('-p', '--web-port', action='store',
                        default=9418, type=int, metavar='N',
                        help='Specify alternate web port [default: 9418]')
args = parser.parse_args()

Handler = http.server.SimpleHTTPRequestHandler

with socketserver.TCPServer(("", args.web_port), Handler) as httpd:
    local_ip = [(s.connect(('8.8.8.8', 1)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1]
    print("viewer on http://%s:%d" % (local_ip, args.web_port))
    httpd.serve_forever()

https://codefellows.github.io/sea-python-401d4/lectures/sockets.html

더 살펴보자


  1. SOCK_STREAM(TCP)

  1. SOCK_DGRAM(UDP)
profile
pllpokko@alumni.kaist.ac.kr

0개의 댓글