1套接字IP4和简单的客户服务端
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了1套接字IP4和简单的客户服务端相关的知识,希望对你有一定的参考价值。
#coding=utf-8
import socket
print socket.gethostname() #获取主机名
print socket.gethostbyname(socket.gethostname()) #获取IP地址
try:
print socket.gethostbyname(‘www.163.com‘) #获取远程地址IP
except Exception, e:
raise e
客户端:one_client.py
#coding=utf-8 import socket import sys import argparse host = ‘localhost‘ def echo_client(port,d): #创建IP/tcp连接 sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM) server_address =(host,port) sock.connect(server_address) try: sock.sendall(d) amount_r = 0 amount_e = len(d) while amount_r<amount_e: data= sock.recv(16) amount_r+=len(data) except socket.errno,e: print ‘socket error %s‘%str(e) except Exception, e: raise e finally: sock.close() if __name__ ==‘__main__‘: parse = argparse.ArgumentParser(description=‘Sock‘) parse.add_argument(‘-p‘,action=‘store‘,dest=‘port‘,type=int,required=True) g = parse.parse_args() port = g.port while True: v = raw_input(‘input:‘) if v == ‘exit‘: break; else: echo_client(port,v)
服务端:one_server.py
#coding=utf-8 import socket import sys import argparse host = ‘localhost‘ data_payload=2048 backlog=5 def echo_server(port): #创建TCP连接 sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM) #启用 地址端口 sock.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) #绑定端口 server_address = (host,port) print "Starting up echo server on %s port %s"%server_address sock.bind(server_address) sock.listen(backlog) while True: # print ‘waiting to receive message form client‘ client,address = sock.accept() data = client.recv(data_payload) if data: print "Data:%s"%data client.send(data) # print "send %s bytes back to %s"%(data,address) client.close() if __name__=="__main__": parser = argparse.ArgumentParser(description=‘Socket Server Example‘) parser.add_argument(‘-p‘,action=‘store‘,dest=‘port‘,type=int,required=True) given_atgs=parser.parse_args() post=given_atgs.port echo_server(post)
本文出自 “anaf” 博客,谢绝转载!
以上是关于1套接字IP4和简单的客户服务端的主要内容,如果未能解决你的问题,请参考以下文章