首页 > 代码库 > 1套接字IP4和简单的客户服务端

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=http://www.mamicode.com/ sock.recv(16)>

服务端: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和简单的客户服务端