Python 클라이언트 및 서버의 간단한 네트워크 프로그래밍 예

黄舟
풀어 주다: 2017-05-28 11:11:08
원래의
1904명이 탐색했습니다.

이 글은 주로 Python간단한 네트워크프로그래밍을 소개하고, 클라이언트와 서버의 구체적인 구현 기술과 관련 Notes에 대해 자세히 설명합니다. 필요한 친구들이 참고할 수 있습니다

이 글은 예제를 통해 Python으로 간단한 네트워크 프로그래밍을 설명합니다. . 참고할 수 있도록 모든 사람과 공유하세요. 세부 사항은 다음과 같습니다.

콘텐츠 디렉터리

1. 클라이언트(client.py)
2. 서버(server.py)

1. 클라이언트(client.py) )

import socket
import sys
port = 70
host = sys.argv[1]
filename = sys.argv[2]
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
fd = s.makefile("rw", 0)
fd.write(filename + "\n")
for line in fd.readlines():
  sys.stdout.write(line)
로그인 후 복사

프로그램은 소켓.socket()을 통해 소켓을 생성합니다. 매개변수는 TCP 통신에 인터넷 소켓이 필요함을 시스템에 알려줍니다. 그런 다음 프로그램은 원격 호스트 이름에 연결하고 파일 이름을 제공합니다. 최종적으로 응답을 받은 후 화면에 인쇄합니다.

Test

python client.py quux.org /
로그인 후 복사

Display

iWelcome to gopher at quux.org! fake  (NULL) 0
i  fake  (NULL) 0
iThis server has a lot of information of historic interest, fake  (NULL) 0
ifunny, or just plain entertaining -- all presented in Gopher. fake  (NULL) 0
iThere are many mirrors here of rare or valuable files with the fake  (NULL) 0
iaim to preserve them in case their host disappears. PLEASE READ  fake  (NULL) 0
i"About This Server" FOR IMPORTANT NOTES AND LEGAL INFORMATION. fake  (NULL) 0
i  fake  (NULL) 0
0About This Server /About This Server.txt gopher.quux.org 70 +
1Archives  /Archives  gopher.quux.org 70 +
1Books /Books gopher.quux.org 70 +
1Communication /Communication gopher.quux.org 70 +
iThis directory contains the entire text of the book  fake  (NULL) 0
i"We the Media: Grassroots Journalism by the People, for the People"  fake  (NULL) 0
iby Dan Gillmor in various formats. fake  (NULL) 0
i  fake  (NULL) 0
iFeel free to download and enjoy.  fake  (NULL) 0
1Computers /Computers gopher.quux.org 70 +
1Current Issues and Events (Updated Apr. 23, 2002) /Current  gopher.quux.org 70 +
1Development Projects  /devel gopher.quux.org 70 +
0Gopher's 10th Anniversary /3.0.0.txt gopher.quux.org 70
1Government, Politics, Law, and Conflict  /Government gopher.quux.org 70 +
0How To Help  /How To Help.txt  gopher.quux.org 70 +
1Humor and Fun /Humor and Fun gopher.quux.org 70 +
1Index to Quux.Org /Archives/index gopher.quux.org 70
1Internet  /Internet  gopher.quux.org 70 +
1Other Gopher Servers  /Software/Gopher/servers  gopher.quux.org 70
1People /People gopher.quux.org 70 +
1Reference /Reference gopher.quux.org 70 +
1Software and Downloads /Software  gopher.quux.org 70 +
1The Gopher Project /Software/Gopher  gopher.quux.org 70
0What's New /whatsnew.txt  gopher.quux.org 70 + 
로그인 후 복사

2. 서버(server.py)

# coding: utf-8
import socket
host = ''
port = 51421
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((host, port))
s.listen(1)        #每次最多只有一个等候处理
print "Server is running on port %d; press Ctrl-C to terminate." %port
while 1:
  clientsock, clientaddr = s.accept()
  clientfile = clientsock.makefile('rw', 0)
  clientfile.write("Welcome, " + str(clientaddr) + "\n")
  clientfile.write("Please enter a string: ")
  line = clientfile.readline().strip()
  clientfile.write("You entered %d characters. \n" %len(line))
  clientfile.close()
  clientsock.close()
로그인 후 복사

소켓을 생성하고 재사용 가능(재사용 가능)으로 설정하고 포트 번호를 51421로 바인드합니다(1024보다 큰 경우 선택 사항). 값), 클라이언트의 요청 대기를 시작하려면 Listen() 함수 를 호출하고 처리 대기 중인 링크를 최대 1개 설정하세요.

메인루프는 a.accept() 함수를 호출하여 시작됩니다. 프로그램은 사용자 입력을 받기 위해 클라이언트에 연결한 후 즉시 중지됩니다.

예제 실행

먼저 server.py를 실행

python server.py
로그인 후 복사

다른 터미널을 열고 localhost의 포트 51421에 연결합니다.

아아아아

위 내용은 Python 클라이언트 및 서버의 간단한 네트워크 프로그래밍 예의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!