client客户端

Python轻易互连网编制程序示例【客户端与服务端】,python网络编程示例

本文实例讲述了Python轻易网络编制程序。分享给大家供大家仿效,具体如下:

剧情目录

  1. 客户端(client.py)
  2. 服务端(server.py)

一、客户端(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.socket()创设3个Socket,参数告诉系统需求3个Internet
Socket实行TCP通讯。接着程序链接远程的主机名,并提供文件名。最后收获响应后在显示屏上打字与印刷出来。

测试

python client.py quux.org /

客户端与服务端,Python简单网络编程示例。显示

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 + 

二、服务端(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()

创制二个socket,设置成可复用的(reusable),绑定端口号514二一(可选大于102四的任一值),调用listen()函数,开端等候来自客户端的乞请,同期设定最多只有多少个等候管理的链接。

主循环对a.accept()函数调用初阶,程序连接三个客户端后及时甘休,接收用户的输入。

运行1个事例

率先运营server.py

python server.py

另开一个巅峰,连接localhost的514贰一端口。 

[email protected]:~/web$ telnet localhost 51421
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Welcome, ('127.0.0.1', 59853)
Please enter a string: mm
You entered 2 characters.
Connection closed by foreign host.

越来越多关于Python相关内容感兴趣的读者可查看本站专项论题:《Python
Socket编制程序技艺总计》、《Python函数使用技巧总结》、《Python字符串操作工夫汇总》、《Python入门与进阶优秀教程》及《Python文件与目录操作本事汇总》

盼望本文所述对大家Python程序设计有所协助。

本文实例讲述了Python不难互连网编制程序。分享给大家供我们参照他事他说加以调查,具体如下:…

python 互连网编制程序——客户端

互连网通讯的着力接口是socket,它扩展了操作系统的基本I/O到网络网络通讯。socket能够经过socket()函数来创设,通过connect()函数来延续。获得了socket,能够分明本地和长途端点的IP地址和端口号。socket对分化的情商以来都是1种通用的接口,它能够拍卖TCP和UDP通讯。

 

成立socket需求两步:创设socket对象、连接到长途服务器上

 

 

import socket
print "Creating socket"
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  #指明通信类型和协议家族
print "Done!"

print "Connecting to remote host..."
s.connect(("www.baidu.com", 80))
print "Done"

 

运转结果

 

1

2

3

4

Creating socket

Done!

Connecting to remote host…

Done

查找端口号

 

通过协商名和端口名查找端口号(unix系统能够在etc/services中找到相应的端口号)

 

 

import socket
print "Creating socket"
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print "Done!"

print "Looking up port number..."
port = socket.getservbyname("http", "tcp")
print port
print "done!"

print "Connecting to remote host..."
s.connect(("www.baidu.com", port))
print "Done!!"

 

 

运作结果

 

1

2

3

4

5

6

7

Creating socket

Done!

Looking up port number…

80

done!

Connecting to remote host…

Done!!

从socket得到音讯

 

 

import socket
print "Creating socket"
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print "Done!"

print "Looking up port number..."
port = socket.getservbyname("http", "tcp")
print port
print "done!"

print "Connecting to remote host..."
s.connect(("www.baidu.com", port))
print "Done!!"

print "Connected from", s.getsockname()  #获得本地机器的ip和端口号(端口号由操作系统随机分配,每次都不一样)
print "Connected to", s.getpeername()    #获得连接机器的ip和端口号

 

 

贰次运营结果

 

1

2

3

4

5

6

7

8

9

Creating socket

Done!

Looking up port number…

80

done!

Connecting to remote host…

Done!!

Connected from (‘192.168.209.129’, 56245)

Connected to (‘220.181.112.244’, 80)

利用socket通信

 

socket对象:send()、sendto()、recv()、recvfrom()

 

文件类对象:read()、write()、readline()

 

管理错误

 

 

import socket, sys

host = sys.argv[1]
textport = sys.argv[2]
filename = sys.argv[3]

try:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error, e:
    print "Strange error creating socket: %s" % e
    sys.exit(1)

try:
    port = int(textport)
except ValueError:
    try:
        port = socket.getservbyname(textport, 'tcp')
    except socket.error, e:
        print "Couldn't find your port: %s" % e
        sys.exit(1)

try:
    s.connect((host, port))
except socket.gaierror, e:
    print "Address-related error connecting to server: %s" %e
    sys.exit(1)
except socket.error, e:
    print "Connection error: %s" %e
    sys.exit(1)

try:
    s.sendall("GET %s HTTP/1.0\r\n\r\n" % filename)
except socket.error, e:
    print "Error sending data: %s" %e
    sys.exit(1)
print "---------------------------------------"

while 1:
    try:
        buf = s.recv(2048)
    except socket.error, e:
        print "========Error receving data: %s=======" %e
        sys.exit(1)
    if not len(buf):
        break
    sys.stdout.write(buf)
print "---------------------------------------"

 

 

改进

 

 

#coding: utf-8
import socket
import sys
import time

host = sys.argv[1]
textport = sys.argv[2]
filename = sys.argv[3]

try:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error, e:
    print "Strange error creating socket: %s" % e
    sys.exit(1)

try:
    port = int(textport)
except ValueError:
    print "ValueError"
    try:
        port = socket.getservbyname(textport, 'tcp')
    except socket.error, e:
        print "Couldn't find your port: %s" % e
        sys.exit(1)

try:
    s.connect((host, port))
except socket.gaierror, e:   #主机名不对
    print "Address-related error connecting to server: %s" %e
    sys.exit(1)
except socket.error, e:      #连接远程主机有问题
    print "Connection error: %s" %e
    sys.exit(1)

print "Sleepping........."
time.sleep(10)
print "Continuing."

try:
    s.sendall("GET %s HTTP/1.0\r\n\r\n" % filename)
except socket.error, e:
    print "Error sending data: %s" % e
    sys.exit(1)

try: 
    s.shutdown(1)
except socket.error, e:
    print "Error sending data (detected by shutdown):%s" % e
    sys.exit(1)


print "---------------------------------------"
while 1:
    try:
        buf = s.recv(2048)
        print "try"
    except socket.error, e:
        print "========Error receving data: %s=======" %e
        sys.exit(1)

    if not len(buf):  #接受的为空
        print "breaK"
        break
    sys.stdout.write(buf)
print "---------------------------------------"

 

 

互联网编程——客户端
互联网通信的主导接口是socket,它扩充了操作系统的基本I/O到互联网互连网通讯。socket能够由此socket()函数来创建,通过…

复制代码 代码如下:

if __name__ == ‘__main__’:  
    import socket  
    import os
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  
    sock.connect((‘localhost’, 8001))  
    import time  
    time.sleep(2)  
    sock.send(‘1’)  
    print sock.recv(1024)

网站地图xml地图