最近几天的一些代码。

2017.10.3

IP.py

#!/usr/bin/python
import socket
 
host_name = socket.gethostname()
print "hostname:%s" % host_name
print "IP address: %s" % socket.gethostbyname(host_name)

#!/usr/bin/python
import socket
 
host_name = socket.gethostname()
print "hostname:%s" % host_name
print "IP address: %s" % socket.gethostbyname(host_name)

MyServer.py [inter]

#!/usr/bin/python

#装载socket通讯
import socket

#设置本机socket
LocalSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

#得到本机的ip地址
HostName = socket.gethostname()
print "服务器名称:%s" % HostName
HostIp = socket.gethostbyname(HostName)
print "IP 地址: %s" % HostIp

#为Socket寻找端口
for PortNow in range(1001,10000) :
    print "\n[Server] 正在尝试本机端口:", PortNow
    try :
        LocalSocket.bind(( HostIp , PortNow ))
        print "[Server]端口:",PortNow,"设置成功"
        break
    except Exception, e:
        print "[Server]本机端口:",PortNow,"设置失败"
        print Exception,":"
        print e

#最大连接数
LocalSocket.listen(5)

#Operating
while True :
    #输入操作Code
    OperateCode = int ( input("\n[Server] 请输入操作码:") )
    if OperateCode == -1 :
        print "[Server] 操作终止!"
        break
    else :
        print "[Server] OperateCode = ",OperateCode
    print "[Server] 正在等待建立连接..."
    #OperateCode functions
    """
    if OperateCode == 1 :
        print "[Server] Set time out for 10 second!"
        try :
            LocalSocket.settimeout(10)
            print "Set successfully"
        except Exception,e :
            print "Set timeout Error"
            print Exception,":"
            print e
    """
    #等待建立连接
    ClientSocket,Address = LocalSocket.accept()
    #输出连接信息
    print "[Server] 成功建立连接:"
    print ClientSocket," ",Address,"\n"
    #从用户收取2048b信息
    print "[Server] 等待客户的响应..."
    Message = ClientSocket.recv( 2048 )
    if Message != "" :
        print "[Server] 收到信息:",Message
    else :
        print "[Server] 未受到任何信息!"
    #向客户发送信息
    ClientSocket.send("{Server} Message get successfully!\n")
    #关闭与客户连接
    print "[Server] 关闭与客户的联系..."
    ClientSocket.close()

#ShutDown PortNow...
print "正在关闭本机端口..."
LocalSocket.close()


#!/usr/bin/python

#装载socket通讯
import socket

#设置本机socket
LocalSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

#得到本机的ip地址
HostName = socket.gethostname()
print "服务器名称:%s" % HostName
HostIp = socket.gethostbyname(HostName)
print "IP 地址: %s" % HostIp

#为Socket寻找端口
for PortNow in range(1001,10000) :
    print "\n[Server] 正在尝试本机端口:", PortNow
    try :
        LocalSocket.bind(( HostIp , PortNow ))
        print "[Server]端口:",PortNow,"设置成功"
        break
    except Exception, e:
        print "[Server]本机端口:",PortNow,"设置失败"
        print Exception,":"
        print e

#最大连接数
LocalSocket.listen(5)

#Operating
while True :
    #输入操作Code
    OperateCode = int ( input("\n[Server] 请输入操作码:") )
    if OperateCode == -1 :
        print "[Server] 操作终止!"
        break
    else :
        print "[Server] OperateCode = ",OperateCode
    print "[Server] 正在等待建立连接..."
    #OperateCode functions
    """
    if OperateCode == 1 :
        print "[Server] Set time out for 10 second!"
        try :
            LocalSocket.settimeout(10)
            print "Set successfully"
        except Exception,e :
            print "Set timeout Error"
            print Exception,":"
            print e
    """
    #等待建立连接
    ClientSocket,Address = LocalSocket.accept()
    #输出连接信息
    print "[Server] 成功建立连接:"
    print ClientSocket," ",Address,"\n"
    #从用户收取2048b信息
    print "[Server] 等待客户的响应..."
    Message = ClientSocket.recv( 2048 )
    if Message != "" :
        print "[Server] 收到信息:",Message
    else :
        print "[Server] 未受到任何信息!"
    #向客户发送信息
    ClientSocket.send("{Server} Message get successfully!\n")
    #关闭与客户连接
    print "[Server] 关闭与客户的联系..."
    ClientSocket.close()

#ShutDown PortNow...
print "正在关闭本机端口..."
LocalSocket.close()

MyClient.py

#!/usr/bin/python

#装载一下socket通讯
import socket

#装载正则表达式
import re

#定义服务端对象
ServerSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

#输入服务器的ip地址
HostIp = str( raw_input("[Client] Input host ip address:") )

#检测是否为本机
if re.match( "/localip",HostIp,re.I ) :
    print "You choose to use local Ip!"
    HostName = socket.gethostname()
    HostIp = socket.gethostbyname(HostName)
elif re.match( "/localhost",HostIp,re.I ) :
    print "You choose local host!"
    try :
        HostIp = socket.gethostbyname('localhost')
        print "get host ip successfully!"
    except Exception, e:
        print "Get host ip failed!"
        print Exception,":"
        print e,"\n"
        print "[Client] Choose local ip instead!"
        HostName = socket.gethostname()
        HostIp = socket.gethostbyname(HostName)
    print "[Client] This function is still under debug"

#输出确定的ip地址
print "[Client] host ip address:",HostIp

#输入当前端口
while True:
    PortNow=int(input("\n[Client] Please Input PortNow:"))
    #尝试设置端口
    try :
        ServerSocket.connect( ( HostIp , PortNow ) )
        print "access PortNow successfully!"
        #设置成功则退出
        break
    except Exception,e :
        print "PortNow is not accessable!"
        #输出错误信息
        print Exception,":"
        print e

#输入信息
Message = str( raw_input("[Client] Input Your Message:") )

#尝试向端口发送信息
try :
    ServerSocket.send( Message )
    print "[Client] Message send success!"
except Exception,e :
    print "[Client] Error when send a message to"
    print str(ServerSocket),"\n"
    
    #输出错误信息
    print Exception,":"
    print e

#接受服务端反馈2048b
try :
    FeedBack = ServerSocket.recv(2048)
    print "[Client] Get Feed Back!"
except Exception,e :
    print "[Client] Error When get feed back!"
    print Exception,":"
    print e

#输出反馈信息
if FeedBack == "" :
    print "[Client] no feed back!"
else :
    print "Feedback =",FeedBack
#关闭端口
ServerSocket.close()


#!/usr/bin/python

#装载一下socket通讯
import socket

#装载正则表达式
import re

#定义服务端对象
ServerSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

#输入服务器的ip地址
HostIp = str( raw_input("[Client] Input host ip address:") )

#检测是否为本机
if re.match( "/localip",HostIp,re.I ) :
    print "You choose to use local Ip!"
    HostName = socket.gethostname()
    HostIp = socket.gethostbyname(HostName)
elif re.match( "/localhost",HostIp,re.I ) :
    print "You choose local host!"
    try :
        HostIp = socket.gethostbyname('localhost')
        print "get host ip successfully!"
    except Exception, e:
        print "Get host ip failed!"
        print Exception,":"
        print e,"\n"
        print "[Client] Choose local ip instead!"
        HostName = socket.gethostname()
        HostIp = socket.gethostbyname(HostName)
    print "[Client] This function is still under debug"

#输出确定的ip地址
print "[Client] host ip address:",HostIp

#输入当前端口
while True:
    PortNow=int(input("\n[Client] Please Input PortNow:"))
    #尝试设置端口
    try :
        ServerSocket.connect( ( HostIp , PortNow ) )
        print "access PortNow successfully!"
        #设置成功则退出
        break
    except Exception,e :
        print "PortNow is not accessable!"
        #输出错误信息
        print Exception,":"
        print e

#输入信息
Message = str( raw_input("[Client] Input Your Message:") )

#尝试向端口发送信息
try :
    ServerSocket.send( Message )
    print "[Client] Message send success!"
except Exception,e :
    print "[Client] Error when send a message to"
    print str(ServerSocket),"\n"
    
    #输出错误信息
    print Exception,":"
    print e

#接受服务端反馈2048b
try :
    FeedBack = ServerSocket.recv(2048)
    print "[Client] Get Feed Back!"
except Exception,e :
    print "[Client] Error When get feed back!"
    print Exception,":"
    print e

#输出反馈信息
if FeedBack == "" :
    print "[Client] no feed back!"
else :
    print "Feedback =",FeedBack
#关闭端口
ServerSocket.close()

2017.10.4

Server.py [ctnd]

#!/usr/bin/python

#正则表达式
import re

#局域网通信
import socket

#创建本地端口
LocalSocket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)

#得到本机的ip地址
host_name = socket.gethostname()
print "hostname:%s" % host_name
host_ip = socket.gethostbyname(host_name)
print "IP address: %s" % host_ip

#设置反馈状态
FeedBackMode = 0

#素数判断函数
def is_prime(num):
    #整数化
    num = long(num)
    if num <= 1 :
        return False
    if num == 2 :
        return True
    i = 2
    while i*i <= num :
        if num % i == 0 :
            return False
        i = i + 1
    return True

#检测指令
def InstructionCheck(Message) :
    #定义全局变量
    global FeedBackMode
    #分析指令标志
    if(Message[0]!='/') :return False
    if re.match("/float",Message,re.I) :
        print "[Instruction] /float"
        FeedBackMode = 0
        return True
    elif re.match("/sqrt",Message,re.I) :
        print "[Instruction] /sqrt"
        FeedBackMode = 1
        return True
    elif re.match("/prime",Message,re.I) :
        print "[Instruction] /prime"
        FeedBackMode = 2
        return True
    else :
        print "[Server] Unkonwn Instruction:",Message
        FeedBackMode = -1
        return True

#定义信息回应方式
def ReturnCode(Message) :
    if FeedBackMode == 0 :
        return str(float(Message)*2)
    elif FeedBackMode == 1 :
        return str(float(Message)**0.5)
    elif FeedBackMode == 2 :
        return str(is_prime(Message))
    else :
        return "[Server] FeedBackMode not defined!"

#最后确定的端口编号
PortSuc = 0

#检测并开启输出端口
for PortNow in range(1001,10000) :
    print "\n[Server] Try Port:",PortNow
    try :
        LocalSocket.bind(( host_ip , PortNow ))
        print "[Server] Set Successfully!"
        PortSuc = PortNow
        break
    except Exception,e :
        print "[Server] Port:",PortNow," not allowed..."
        print Exception,":"
        print e

#最大连接数
LocalSocket.listen(5)

#开始传输数据
print "[Server] Data Start..."
while True :
    #等待建立连接
    print "[Server] Wait for connection..."
    ClientSocket,Address = LocalSocket.accept()
    print "[Server] Get connection Sucessfully!"
    #输出连接信息
    print ClientSocket," ",Address,"\n"
    while True :
        #从用户端得到信息
        print "[Server] Wait for apply from Client..."
        Message = ClientSocket.recv(4096)
        #检测终止指令
        if re.match("/end",Message,re.I) :
            print "[Server] End instruction checked!"
            break
        #检测其他指令
        if InstructionCheck(Message) :
            print "change feedbackmode to:",FeedBackMode
            continue
        #检测非法终止
        if Message=="" :
            print "[Server] Get nothing!"
            break
        #输出反馈信息
        print "[Server] Get message:",Message
        RetCode = ReturnCode(Message)
        print "[Server] RetCode should be:",RetCode
        ClientSocket.send(RetCode)
    ClientSocket.close()
    break

LocalSocket.close()


#!/usr/bin/python

#正则表达式
import re

#局域网通信
import socket

#创建本地端口
LocalSocket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)

#得到本机的ip地址
host_name = socket.gethostname()
print "hostname:%s" % host_name
host_ip = socket.gethostbyname(host_name)
print "IP address: %s" % host_ip

#设置反馈状态
FeedBackMode = 0

#素数判断函数
def is_prime(num):
    #整数化
    num = long(num)
    if num <= 1 :
        return False
    if num == 2 :
        return True
    i = 2
    while i*i <= num :
        if num % i == 0 :
            return False
        i = i + 1
    return True

#检测指令
def InstructionCheck(Message) :
    #定义全局变量
    global FeedBackMode
    #分析指令标志
    if(Message[0]!='/') :return False
    if re.match("/float",Message,re.I) :
        print "[Instruction] /float"
        FeedBackMode = 0
        return True
    elif re.match("/sqrt",Message,re.I) :
        print "[Instruction] /sqrt"
        FeedBackMode = 1
        return True
    elif re.match("/prime",Message,re.I) :
        print "[Instruction] /prime"
        FeedBackMode = 2
        return True
    else :
        print "[Server] Unkonwn Instruction:",Message
        FeedBackMode = -1
        return True

#定义信息回应方式
def ReturnCode(Message) :
    if FeedBackMode == 0 :
        return str(float(Message)*2)
    elif FeedBackMode == 1 :
        return str(float(Message)**0.5)
    elif FeedBackMode == 2 :
        return str(is_prime(Message))
    else :
        return "[Server] FeedBackMode not defined!"

#最后确定的端口编号
PortSuc = 0

#检测并开启输出端口
for PortNow in range(1001,10000) :
    print "\n[Server] Try Port:",PortNow
    try :
        LocalSocket.bind(( host_ip , PortNow ))
        print "[Server] Set Successfully!"
        PortSuc = PortNow
        break
    except Exception,e :
        print "[Server] Port:",PortNow," not allowed..."
        print Exception,":"
        print e

#最大连接数
LocalSocket.listen(5)

#开始传输数据
print "[Server] Data Start..."
while True :
    #等待建立连接
    print "[Server] Wait for connection..."
    ClientSocket,Address = LocalSocket.accept()
    print "[Server] Get connection Sucessfully!"
    #输出连接信息
    print ClientSocket," ",Address,"\n"
    while True :
        #从用户端得到信息
        print "[Server] Wait for apply from Client..."
        Message = ClientSocket.recv(4096)
        #检测终止指令
        if re.match("/end",Message,re.I) :
            print "[Server] End instruction checked!"
            break
        #检测其他指令
        if InstructionCheck(Message) :
            print "change feedbackmode to:",FeedBackMode
            continue
        #检测非法终止
        if Message=="" :
            print "[Server] Get nothing!"
            break
        #输出反馈信息
        print "[Server] Get message:",Message
        RetCode = ReturnCode(Message)
        print "[Server] RetCode should be:",RetCode
        ClientSocket.send(RetCode)
    ClientSocket.close()
    break

LocalSocket.close()

Client.py [ctnd]

#!/usr/bin/python

#装载正则表达式
import re

#装载时间函数
import time

#装载通信
import socket

#定义服务端对象
ServerSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

#输入服务器的ip地址
HostIp = str( raw_input("[Client] Input host ip address:") )

#检测是否为本机
if re.match( "/localip",HostIp,re.I ) :
    print "You choose to use local Ip!"
    HostName = socket.gethostname()
    HostIp = socket.gethostbyname(HostName)
elif re.match( "/localhost",HostIp,re.I ) :
    print "You choose local host!"
    try :
        HostIp = socket.gethostbyname('localhost')
        print "get host ip successfully!"
    except Exception, e:
        print "Get host ip failed!"
        print Exception,":"
        print e,"\n"
        print "[Client] Choose local ip instead!"
        HostName = socket.gethostname()
        HostIp = socket.gethostbyname(HostName)
    print "[Client] This function is still under debug"

#输出确定的ip地址
print "[Client] host ip address:",HostIp

#输入当前端口
while True:
    PortNow=int(input("\n[Client] Please Input PortNow:"))
    #尝试设置端口
    try :
        ServerSocket.connect( ( HostIp , PortNow ) )
        print "access PortNow successfully!"
        #设置成功则退出
        break
    except Exception,e :
        print "PortNow is not accessable!"
        #输出错误信息
        print Exception,":"
        print e

#开始数据传送
while True :
    #数据传送测试
    for i in range(1001,1021) :
        if (i%2==1) :
            #对奇数判断是否是质数
            print "[Client] send message:","/prime"
            ServerSocket.send("/prime")
        else :
            #对偶数开平方根
            print "[Client] send message:","/sqrt"
            ServerSocket.send("/sqrt")
        print "[Client] send message:",str(i)
        #等待反应0.2s
        time.sleep(0.2)
        ServerSocket.send(str(i))
        #接收反馈4096b
        print "[Client] Wait feedback..."
        FeedBack=ServerSocket.recv(4096);
        print "[Client] feedback:",FeedBack
    #终止数据传输
    print "[Client] send End flag"
    ServerSocket.send('/end')
    break

#关闭端口
ServerSocket.close()



#!/usr/bin/python

#装载正则表达式
import re

#装载时间函数
import time

#装载通信
import socket

#定义服务端对象
ServerSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

#输入服务器的ip地址
HostIp = str( raw_input("[Client] Input host ip address:") )

#检测是否为本机
if re.match( "/localip",HostIp,re.I ) :
    print "You choose to use local Ip!"
    HostName = socket.gethostname()
    HostIp = socket.gethostbyname(HostName)
elif re.match( "/localhost",HostIp,re.I ) :
    print "You choose local host!"
    try :
        HostIp = socket.gethostbyname('localhost')
        print "get host ip successfully!"
    except Exception, e:
        print "Get host ip failed!"
        print Exception,":"
        print e,"\n"
        print "[Client] Choose local ip instead!"
        HostName = socket.gethostname()
        HostIp = socket.gethostbyname(HostName)
    print "[Client] This function is still under debug"

#输出确定的ip地址
print "[Client] host ip address:",HostIp

#输入当前端口
while True:
    PortNow=int(input("\n[Client] Please Input PortNow:"))
    #尝试设置端口
    try :
        ServerSocket.connect( ( HostIp , PortNow ) )
        print "access PortNow successfully!"
        #设置成功则退出
        break
    except Exception,e :
        print "PortNow is not accessable!"
        #输出错误信息
        print Exception,":"
        print e

#开始数据传送
while True :
    #数据传送测试
    for i in range(1001,1021) :
        if (i%2==1) :
            #对奇数判断是否是质数
            print "[Client] send message:","/prime"
            ServerSocket.send("/prime")
        else :
            #对偶数开平方根
            print "[Client] send message:","/sqrt"
            ServerSocket.send("/sqrt")
        print "[Client] send message:",str(i)
        #等待反应0.2s
        time.sleep(0.2)
        ServerSocket.send(str(i))
        #接收反馈4096b
        print "[Client] Wait feedback..."
        FeedBack=ServerSocket.recv(4096);
        print "[Client] feedback:",FeedBack
    #终止数据传输
    print "[Client] send End flag"
    ServerSocket.send('/end')
    break

#关闭端口
ServerSocket.close()

2017.10.5

Receiver.py [msgcon]

#!/usr/bin/python

#正则表达式
import re

#局域网通信
import socket

#创建本地端口
LocalSocket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)

#输出错误信息
def SendErrMsg(message,exception,e) :
    if message!="" :print message
    print "解释器给出的错误原因如下:"
    print exception,":"
    print e

#暂停程序
def Pause() :
    raw_input("请按任意键继续...")

#得到本机的ip地址
def GetHostIp(Tip = True) :
    if Tip == True : print "\n[服务端] 正在尝试获得本机IP地址..."
    #定义变量
    host_name = ""
    host_ip = ""
    #尝试获得本机名称
    try :
        host_name = socket.gethostname()
        if Tip == True : print "当前名称:%s" % host_name
    except Exception,e :
        #出错
        SendErrMsg("[服务端] 获得本机名称时出错",Exception,e)
        Pause()
    #尝试得到本机IP地址
    try :
        host_ip = socket.gethostbyname(host_name)
        if Tip == True : print "当前IP地址: %s" % host_ip
    except Exception,e :
        #出错
        SendErrMsg("[服务端] 获得本机IP地址时出错",Exception,e)
        Pause()
    if Tip == True : print "成功获得本机IP地址:[",host_ip,"]"
    return host_ip

#检测并开启输出端口
def StartLocalSocket(HostIp,Tip = True) :
    if Tip == True : print "\n[服务端] 检测并开启输出端口..."
    #尝试端口
    PortSuc = 0
    for PortNow in range( 1001, 10000) :
        if Tip == True : print "\n正在尝试端口:",PortNow
        try :
            LocalSocket.bind(( HostIp , PortNow ))
            if Tip == True : print "[服务端] 设置成功,端口为:[",PortNow,"]"
            #记录成功的端口号
            PortSuc = PortNow
            break
        except Exception,e :
            if Tip == True : print "端口:",PortNow," 不可用..."
            if Tip == True : SendErrMsg("",Exception,e)
    #输出[成功/失败]信息
    if PortSuc != 0 :
        if Tip == True : print "[服务端] 设置成功!"
        return True
    else :
        if Tip == True :
            print "[服务端] 设置失败!"
            Pause()
        return False

#尝试着连接到客户端
def TryConnection() :
    print "[服务端] 正在尝试建立连接..."
    #得到当前的IP地址
    HostIpNow = GetHostIp()
    #检测并开启输出端口
    StartLocalSocket(HostIpNow)
    #最大连接数
    LocalSocket.listen(5)
    #等待用户连接
    print "[服务端] 等待用户连接..."
    #设置超时时限
    socket.setdefaulttimeout(20)
    try :
        ClientSocket,Address = LocalSocket.accept()
        print "成功得到与客户端的连接,IP地址:[",Address,"]"
    except Exception,e :
        SendErrMsg("[服务端] 等待连接超时",Exception,e)
        return False
    #信息交换
    print "[服务端] 开始接受信息..."
    while True :
        try :
            ClntMsg = ClientSocket.recv(4096)
            print ClntMsg
        except Exception,e :
            SendErrMsg("[服务端] 连接超时",Exception,e)
            break
        if re.match( "/end",ClntMsg, re.I ) :
            print "[服务端] 检测到文件终止符"
            break
    #关闭端口
    ClientSocket.close()
    LocalSocket.close()
    #成功结束一次连接
    return True

#主程序从这里开始,程序注释
"""
这是这个程序主程序的开始
编写时间:2017.10.5
程序作者:NEYC GGN
"""

#尝试建立连接
TryConnection()

#!/usr/bin/python

#正则表达式
import re

#局域网通信
import socket

#创建本地端口
LocalSocket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)

#输出错误信息
def SendErrMsg(message,exception,e) :
    if message!="" :print message
    print "解释器给出的错误原因如下:"
    print exception,":"
    print e

#暂停程序
def Pause() :
    raw_input("请按任意键继续...")

#得到本机的ip地址
def GetHostIp(Tip = True) :
    if Tip == True : print "\n[服务端] 正在尝试获得本机IP地址..."
    #定义变量
    host_name = ""
    host_ip = ""
    #尝试获得本机名称
    try :
        host_name = socket.gethostname()
        if Tip == True : print "当前名称:%s" % host_name
    except Exception,e :
        #出错
        SendErrMsg("[服务端] 获得本机名称时出错",Exception,e)
        Pause()
    #尝试得到本机IP地址
    try :
        host_ip = socket.gethostbyname(host_name)
        if Tip == True : print "当前IP地址: %s" % host_ip
    except Exception,e :
        #出错
        SendErrMsg("[服务端] 获得本机IP地址时出错",Exception,e)
        Pause()
    if Tip == True : print "成功获得本机IP地址:[",host_ip,"]"
    return host_ip

#检测并开启输出端口
def StartLocalSocket(HostIp,Tip = True) :
    if Tip == True : print "\n[服务端] 检测并开启输出端口..."
    #尝试端口
    PortSuc = 0
    for PortNow in range( 1001, 10000) :
        if Tip == True : print "\n正在尝试端口:",PortNow
        try :
            LocalSocket.bind(( HostIp , PortNow ))
            if Tip == True : print "[服务端] 设置成功,端口为:[",PortNow,"]"
            #记录成功的端口号
            PortSuc = PortNow
            break
        except Exception,e :
            if Tip == True : print "端口:",PortNow," 不可用..."
            if Tip == True : SendErrMsg("",Exception,e)
    #输出[成功/失败]信息
    if PortSuc != 0 :
        if Tip == True : print "[服务端] 设置成功!"
        return True
    else :
        if Tip == True :
            print "[服务端] 设置失败!"
            Pause()
        return False

#尝试着连接到客户端
def TryConnection() :
    print "[服务端] 正在尝试建立连接..."
    #得到当前的IP地址
    HostIpNow = GetHostIp()
    #检测并开启输出端口
    StartLocalSocket(HostIpNow)
    #最大连接数
    LocalSocket.listen(5)
    #等待用户连接
    print "[服务端] 等待用户连接..."
    #设置超时时限
    socket.setdefaulttimeout(20)
    try :
        ClientSocket,Address = LocalSocket.accept()
        print "成功得到与客户端的连接,IP地址:[",Address,"]"
    except Exception,e :
        SendErrMsg("[服务端] 等待连接超时",Exception,e)
        return False
    #信息交换
    print "[服务端] 开始接受信息..."
    while True :
        try :
            ClntMsg = ClientSocket.recv(4096)
            print ClntMsg
        except Exception,e :
            SendErrMsg("[服务端] 连接超时",Exception,e)
            break
        if re.match( "/end",ClntMsg, re.I ) :
            print "[服务端] 检测到文件终止符"
            break
    #关闭端口
    ClientSocket.close()
    LocalSocket.close()
    #成功结束一次连接
    return True

#主程序从这里开始,程序注释
"""
这是这个程序主程序的开始
编写时间:2017.10.5
程序作者:NEYC GGN
"""

#尝试建立连接
TryConnection()

ClientDebug.py [msgcon]

#!/usr/bin/python

#装载正则表达式
import re

#装载时间函数
import time

#装载通信
import socket

#定义服务端对象
ServerSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

#输入服务器的ip地址
HostIp = str( raw_input("[Client] Input host ip address:") )

#检测是否为本机
if re.match( "/localip",HostIp,re.I ) :
    print "You choose to use local Ip!"
    HostName = socket.gethostname()
    HostIp = socket.gethostbyname(HostName)
elif re.match( "/localhost",HostIp,re.I ) :
    print "You choose local host!"
    try :
        HostIp = socket.gethostbyname('localhost')
        print "get host ip successfully!"
    except Exception, e:
        print "Get host ip failed!"
        print Exception,":"
        print e,"\n"
        print "[Client] Choose local ip instead!"
        HostName = socket.gethostname()
        HostIp = socket.gethostbyname(HostName)
    print "[Client] This function is still under debug"

#输出确定的ip地址
print "[Client] host ip address:",HostIp

#输入当前端口
while True:
    PortNow=int(input("\n[Client] Please Input PortNow:"))
    #尝试设置端口
    try :
        ServerSocket.connect( ( HostIp , PortNow ) )
        print "access PortNow successfully!"
        #设置成功则退出
        break
    except Exception,e :
        print "PortNow is not accessable!"
        #输出错误信息
        print Exception,":"
        print e

#开始数据传送
while True :
    #数据传送测试
    for i in range(1001,1021) :
        try:
            if (i%2==1) :
                #对奇数判断是否是质数
                print "[Client] send message:","/prime"
                ServerSocket.send("/prime")
            else :
                #对偶数开平方根
                print "[Client] send message:","/sqrt"
                ServerSocket.send("/sqrt")
            #等待延时
            time.sleep(0.1)
            print "[Client] send message:",str(i)
            ServerSocket.send(str(i))
            time.sleep(0.1)
        except Exception,e :
            print "[Client] Can't Connet to Server!"
            print Exception,":"
            print e
            break;
        """
        #接收反馈4096b
        print "[Client] Wait feedback..."
        FeedBack=ServerSocket.recv(4096);
        print "[Client] feedback:",FeedBack
        """
    #终止数据传输
    try :
        print "[Client] send End flag"
        ServerSocket.send('/end')
    except Exception,e :
        print "[Client] Can't Connet to Server!"
        print Exception,":"
        print e
    break

#关闭端口
ServerSocket.close()

#!/usr/bin/python

#装载正则表达式
import re

#装载时间函数
import time

#装载通信
import socket

#定义服务端对象
ServerSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

#输入服务器的ip地址
HostIp = str( raw_input("[Client] Input host ip address:") )

#检测是否为本机
if re.match( "/localip",HostIp,re.I ) :
    print "You choose to use local Ip!"
    HostName = socket.gethostname()
    HostIp = socket.gethostbyname(HostName)
elif re.match( "/localhost",HostIp,re.I ) :
    print "You choose local host!"
    try :
        HostIp = socket.gethostbyname('localhost')
        print "get host ip successfully!"
    except Exception, e:
        print "Get host ip failed!"
        print Exception,":"
        print e,"\n"
        print "[Client] Choose local ip instead!"
        HostName = socket.gethostname()
        HostIp = socket.gethostbyname(HostName)
    print "[Client] This function is still under debug"

#输出确定的ip地址
print "[Client] host ip address:",HostIp

#输入当前端口
while True:
    PortNow=int(input("\n[Client] Please Input PortNow:"))
    #尝试设置端口
    try :
        ServerSocket.connect( ( HostIp , PortNow ) )
        print "access PortNow successfully!"
        #设置成功则退出
        break
    except Exception,e :
        print "PortNow is not accessable!"
        #输出错误信息
        print Exception,":"
        print e

#开始数据传送
while True :
    #数据传送测试
    for i in range(1001,1021) :
        try:
            if (i%2==1) :
                #对奇数判断是否是质数
                print "[Client] send message:","/prime"
                ServerSocket.send("/prime")
            else :
                #对偶数开平方根
                print "[Client] send message:","/sqrt"
                ServerSocket.send("/sqrt")
            #等待延时
            time.sleep(0.1)
            print "[Client] send message:",str(i)
            ServerSocket.send(str(i))
            time.sleep(0.1)
        except Exception,e :
            print "[Client] Can't Connet to Server!"
            print Exception,":"
            print e
            break;
        """
        #接收反馈4096b
        print "[Client] Wait feedback..."
        FeedBack=ServerSocket.recv(4096);
        print "[Client] feedback:",FeedBack
        """
    #终止数据传输
    try :
        print "[Client] send End flag"
        ServerSocket.send('/end')
    except Exception,e :
        print "[Client] Can't Connet to Server!"
        print Exception,":"
        print e
    break

#关闭端口
ServerSocket.close()

2017.10.7

给出两个同于import引用的文件。

MyClient.py

#!/usr/bin/python
# -*- encoding: gb2312 -*-

#装载正则表达式
import re

#装载时间函数
import time

#装在通信
import socket

#定义服务端对象
ServerSocket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)

#暂停程序
def Pause() :
    raw_input("请按任意键继续...")

#输出错误信息
def SendErrMsg(message,exception,e) :
    if message!="" :print message
    print "解释器给出的错误原因如下:"
    print exception,":"
    print e

#得到本机的ip地址
def GetHostIp(Tip = False) :
    if Tip == True : print "\n正在尝试获得本机IP地址..."
    #定义变量
    host_name = ""
    host_ip = ""
    #尝试获得本机名称
    try :
        host_name = socket.gethostname()
        if Tip == True : print "当前名称:%s" % host_name
    except Exception,e :
        #出错
        SendErrMsg("获得本机名称时出错",Exception,e)
        Pause()
    #尝试得到本机IP地址
    try :
        host_ip = socket.gethostbyname(host_name)
        if Tip == True : print "当前IP地址: %s" % host_ip
    except Exception,e :
        #出错
        SendErrMsg("获得本机IP地址时出错",Exception,e)
        Pause()
    if Tip == True : print "成功获得本机IP地址:[",host_ip,"]"
    return host_ip

#输入IP地址
def IpInput() :
    HostIp = raw_input("请输入IP地址:")
    #检测是否为本机
    if re.match("/localip$",HostIp,re.I) :
        #得到本机地址
        HostIp = GetHostIp(False)
    elif re.match("/localhost$",HostIp,re.I) :
        #得到localhost地址
        HostIp = socket.gethostbyname('localhost')
    print "IP 地址为:",HostIp
    return HostIp

#向指定端口输出信息
def SendMsg(HostIp,PortNow,Msg) :
    print "正在尝试连接端口..."
     #尝试设置端口
    try :
        ServerSocket.connect( ( HostIp , PortNow ) )
        print "成功和端口建立联系!"
        #设置成功则退出
    except Exception,e :
        print "此端口不可用!"
        #输出错误信息
        print Exception,":"
        print e
        return False
    #尝试向端口输出信息
    try :
        ServerSocket.send(Msg)
        print "信息输出成功!"
    except Exception,e :
        print "信息输出失败!"
        print Exception,":"
        print e
    return True

#得到一个文件的全部内容
def GetFileText(FileName) :
    Fp = open(FileName,"r")
    try :
        #读取全部内容
        Text = Fp.read(-1)
    except Exception,e :
        print "文件[",FileName,"]无法读取!"
        return ""
    return Text


#!/usr/bin/python
# -*- encoding: gb2312 -*-

#装载正则表达式
import re

#装载时间函数
import time

#装在通信
import socket

#定义服务端对象
ServerSocket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)

#暂停程序
def Pause() :
    raw_input("请按任意键继续...")

#输出错误信息
def SendErrMsg(message,exception,e) :
    if message!="" :print message
    print "解释器给出的错误原因如下:"
    print exception,":"
    print e

#得到本机的ip地址
def GetHostIp(Tip = False) :
    if Tip == True : print "\n正在尝试获得本机IP地址..."
    #定义变量
    host_name = ""
    host_ip = ""
    #尝试获得本机名称
    try :
        host_name = socket.gethostname()
        if Tip == True : print "当前名称:%s" % host_name
    except Exception,e :
        #出错
        SendErrMsg("获得本机名称时出错",Exception,e)
        Pause()
    #尝试得到本机IP地址
    try :
        host_ip = socket.gethostbyname(host_name)
        if Tip == True : print "当前IP地址: %s" % host_ip
    except Exception,e :
        #出错
        SendErrMsg("获得本机IP地址时出错",Exception,e)
        Pause()
    if Tip == True : print "成功获得本机IP地址:[",host_ip,"]"
    return host_ip

#输入IP地址
def IpInput() :
    HostIp = raw_input("请输入IP地址:")
    #检测是否为本机
    if re.match("/localip$",HostIp,re.I) :
        #得到本机地址
        HostIp = GetHostIp(False)
    elif re.match("/localhost$",HostIp,re.I) :
        #得到localhost地址
        HostIp = socket.gethostbyname('localhost')
    print "IP 地址为:",HostIp
    return HostIp

#向指定端口输出信息
def SendMsg(HostIp,PortNow,Msg) :
    print "正在尝试连接端口..."
     #尝试设置端口
    try :
        ServerSocket.connect( ( HostIp , PortNow ) )
        print "成功和端口建立联系!"
        #设置成功则退出
    except Exception,e :
        print "此端口不可用!"
        #输出错误信息
        print Exception,":"
        print e
        return False
    #尝试向端口输出信息
    try :
        ServerSocket.send(Msg)
        print "信息输出成功!"
    except Exception,e :
        print "信息输出失败!"
        print Exception,":"
        print e
    return True

#得到一个文件的全部内容
def GetFileText(FileName) :
    Fp = open(FileName,"r")
    try :
        #读取全部内容
        Text = Fp.read(-1)
    except Exception,e :
        print "文件[",FileName,"]无法读取!"
        return ""
    return Text

MyServer.py

#!/usr/bin/python
# -*- encoding: gb2312 -*-

#正则表达式
import re

#局域网通信
import socket

#创建本地端口
LocalSocket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)

#输出错误信息
def SendErrMsg(message,exception,e) :
    if message!="" :print message
    print "解释器给出的错误原因如下:"
    print exception,":"
    print e

#暂停程序
def Pause() :
    raw_input("请按任意键继续...")

#得到本机的ip地址
def GetHostIp(Tip = False) :
    if Tip == True : print "\n正在尝试获得本机IP地址..."
    #定义变量
    host_name = ""
    host_ip = ""
    #尝试获得本机名称
    try :
        host_name = socket.gethostname()
        if Tip == True : print "当前名称:%s" % host_name
    except Exception,e :
        #出错
        SendErrMsg("获得本机名称时出错",Exception,e)
        Pause()
    #尝试得到本机IP地址
    try :
        host_ip = socket.gethostbyname(host_name)
        if Tip == True : print "当前IP地址: %s" % host_ip
    except Exception,e :
        #出错
        SendErrMsg("获得本机IP地址时出错",Exception,e)
        Pause()
    if Tip == True : print "成功获得本机IP地址:[",host_ip,"]"
    return host_ip

#检测并开启输出端口
def StartLocalSocket(HostIp, Range = range(1001, 10000), Tip = False) :
    if Tip == True : print "\n检测并开启输出端口..."
    #尝试端口
    PortSuc = 0
    for PortNow in Range :
        if Tip == True : print "\n正在尝试端口:",PortNow
        try :
            LocalSocket.bind(( HostIp , PortNow ))
            if Tip == True : print "设置成功,端口为:[",PortNow,"]"
            #记录成功的端口号
            PortSuc = PortNow
            break
        except Exception,e :
            if Tip == True : print "端口:",PortNow," 不可用..."
            if Tip == True : SendErrMsg("",Exception,e)
    #输出[成功/失败]信息
    if PortSuc != 0 :
        if Tip == True : print "设置成功!"
        return True
    else :
        if Tip == True :
            print "设置失败!"
            Pause()
        return False

#尝试着连接到客户端
def TryConnection() :
    print "正在尝试建立连接..."
    #得到当前的IP地址
    HostIpNow = GetHostIp()
    #检测并开启输出端口
    StartLocalSocket(HostIpNow)
    #最大连接数
    LocalSocket.listen(5)
    #等待用户连接
    print "等待用户连接..."
    #设置超时时限
    socket.setdefaulttimeout(20)
    try :
        ClientSocket,Address = LocalSocket.accept()
        print "成功得到与客户端的连接,IP地址:[",Address,"]"
    except Exception,e :
        SendErrMsg("等待连接超时",Exception,e)
        return False
    #信息交换
    #定义输出方式
    OutputMode = ""
    print "开始接受信息..."
    while True :
        #尝试读入
        try :
            ClntMsg = ClientSocket.recv(4096)
        except Exception,e :
            SendErrMsg("连接超时",Exception,e)
            break
        #检测指令
        if re.match( "/end$",ClntMsg, re.I ) :
            print "检测到文件终止符"
            break
        elif re.match( "/file ",ClntMsg, re.I ) :
            FilePath = ClntMsg[6:]
            print "重定向文件为 ",FilePath
            if type(OutputMode)==file :
                OutputMode.close()
            OutputMode = open(FilePath,"w")
            continue
        #输出非指令信息
        if OutputMode== "" :
            print ClntMsg
        else :
            OutputMode.write(ClntMsg)
    #关闭输出文件
    if type(OutputMode) == file :
        OutputMode.close()
    #关闭端口
    ClientSocket.close()
    LocalSocket.close()
    #成功结束一次连接
    return True

#!/usr/bin/python
# -*- encoding: gb2312 -*-

#正则表达式
import re

#局域网通信
import socket

#创建本地端口
LocalSocket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)

#输出错误信息
def SendErrMsg(message,exception,e) :
    if message!="" :print message
    print "解释器给出的错误原因如下:"
    print exception,":"
    print e

#暂停程序
def Pause() :
    raw_input("请按任意键继续...")

#得到本机的ip地址
def GetHostIp(Tip = False) :
    if Tip == True : print "\n正在尝试获得本机IP地址..."
    #定义变量
    host_name = ""
    host_ip = ""
    #尝试获得本机名称
    try :
        host_name = socket.gethostname()
        if Tip == True : print "当前名称:%s" % host_name
    except Exception,e :
        #出错
        SendErrMsg("获得本机名称时出错",Exception,e)
        Pause()
    #尝试得到本机IP地址
    try :
        host_ip = socket.gethostbyname(host_name)
        if Tip == True : print "当前IP地址: %s" % host_ip
    except Exception,e :
        #出错
        SendErrMsg("获得本机IP地址时出错",Exception,e)
        Pause()
    if Tip == True : print "成功获得本机IP地址:[",host_ip,"]"
    return host_ip

#检测并开启输出端口
def StartLocalSocket(HostIp, Range = range(1001, 10000), Tip = False) :
    if Tip == True : print "\n检测并开启输出端口..."
    #尝试端口
    PortSuc = 0
    for PortNow in Range :
        if Tip == True : print "\n正在尝试端口:",PortNow
        try :
            LocalSocket.bind(( HostIp , PortNow ))
            if Tip == True : print "设置成功,端口为:[",PortNow,"]"
            #记录成功的端口号
            PortSuc = PortNow
            break
        except Exception,e :
            if Tip == True : print "端口:",PortNow," 不可用..."
            if Tip == True : SendErrMsg("",Exception,e)
    #输出[成功/失败]信息
    if PortSuc != 0 :
        if Tip == True : print "设置成功!"
        return True
    else :
        if Tip == True :
            print "设置失败!"
            Pause()
        return False

#尝试着连接到客户端
def TryConnection() :
    print "正在尝试建立连接..."
    #得到当前的IP地址
    HostIpNow = GetHostIp()
    #检测并开启输出端口
    StartLocalSocket(HostIpNow)
    #最大连接数
    LocalSocket.listen(5)
    #等待用户连接
    print "等待用户连接..."
    #设置超时时限
    socket.setdefaulttimeout(20)
    try :
        ClientSocket,Address = LocalSocket.accept()
        print "成功得到与客户端的连接,IP地址:[",Address,"]"
    except Exception,e :
        SendErrMsg("等待连接超时",Exception,e)
        return False
    #信息交换
    #定义输出方式
    OutputMode = ""
    print "开始接受信息..."
    while True :
        #尝试读入
        try :
            ClntMsg = ClientSocket.recv(4096)
        except Exception,e :
            SendErrMsg("连接超时",Exception,e)
            break
        #检测指令
        if re.match( "/end$",ClntMsg, re.I ) :
            print "检测到文件终止符"
            break
        elif re.match( "/file ",ClntMsg, re.I ) :
            FilePath = ClntMsg[6:]
            print "重定向文件为 ",FilePath
            if type(OutputMode)==file :
                OutputMode.close()
            OutputMode = open(FilePath,"w")
            continue
        #输出非指令信息
        if OutputMode== "" :
            print ClntMsg
        else :
            OutputMode.write(ClntMsg)
    #关闭输出文件
    if type(OutputMode) == file :
        OutputMode.close()
    #关闭端口
    ClientSocket.close()
    LocalSocket.close()
    #成功结束一次连接
    return True

2018.1.26

来一个C语言版本的头文件

PracticalSocket.hpp

#include<cstdio>
#include<windows.h>
#pragma comment(lib, "ws2_32.lib")
#define DELAY (200)

int ContractHost(const char* sendData,char* recData,int recLen){ //给服务器发送信息 
	
	WORD sockVersion = MAKEWORD(2, 2);//一些初始的东西 
    WSADATA data;
    if(WSAStartup(sockVersion, &data)!=0)return -2;//创建失败 
    
	SOCKET sclient = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
	if(sclient == INVALID_SOCKET)return -1;//创建失败
	
	sockaddr_in serAddr;//尝试与主机建立连接 
    serAddr.sin_family = AF_INET;
    serAddr.sin_port = htons(8888);
    serAddr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");//主机
	
	if(connect(sclient, (sockaddr *)&serAddr, sizeof(serAddr)) == SOCKET_ERROR)  
	{ 
	    closesocket(sclient);
	    return -3;//连接失败,一般为主机不存在
	    #define HOST_NOT_EXIST (-3)
	}
	
	send(sclient, sendData, strlen(sendData), 0);
	Sleep(DELAY);
	int ret = recv(sclient, recData, recLen, 0);  
    recData[ret] = 0x00;//set EOS
    closesocket(sclient);
    
    WSACleanup();//最后的一些处理 
    
	return 0;//通信成功
	#define CONTRACT_SUC (0)
}

class ServerSocket{//服务端被以类的形式定义 
	WORD sockVersion;    
    WSADATA wsaData;
    SOCKET slisten;
    sockaddr_in sin;
    SOCKET sClient;
    sockaddr_in remoteAddr;
    int nAddrlen;   
    
    public:
    int InitServer(){//启动 
		sockVersion = MAKEWORD(2,2);
		if(WSAStartup(sockVersion, &wsaData)!=0)
			return -1;//fail
		
		slisten = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);    
	    if(slisten == INVALID_SOCKET)    
	        return -2;//socket error  
	    
	    
	    sin.sin_family = AF_INET;//绑定IP和端口  
	    sin.sin_port = htons(8888);
	    sin.sin_addr.S_un.S_addr = INADDR_ANY;// 127.0.0.1
	    if(bind(slisten, (LPSOCKADDR)&sin, sizeof(sin)) == SOCKET_ERROR)    
	        return -3;//bind error
	    
	    if(listen(slisten, 5) == SOCKET_ERROR)//开始监听 
		    return -4;//listen error
		    
	    nAddrlen = sizeof(remoteAddr);//准备循环接收数据 
		return 0;//suc
	}
	int WaitMessage(char* revData,int recLen){
		sClient = accept(slisten, (SOCKADDR *)&remoteAddr, &nAddrlen);//等待连接
		if(sClient == INVALID_SOCKET) return -1;//accept error
		//inet_ntoa(remoteAddr.sin_addr) 接受到的地址的字符串 
		int ret = recv(sClient, revData, recLen, 0);
        revData[ret] = 0x00;//set EOS
	}
	void Feedback(const char* sendData){//反馈一段信息 
        send(sClient, sendData, strlen(sendData), 0);    
        Sleep(DELAY);//try this
        closesocket(sClient);
	}
	void DestructHost(){//结束一个服务器 
		closesocket(slisten);    
    	WSACleanup();    
	}
};

#include<cstdio>
#include<windows.h>
#pragma comment(lib, "ws2_32.lib")
#define DELAY (200)

int ContractHost(const char* sendData,char* recData,int recLen){ //给服务器发送信息 
	
	WORD sockVersion = MAKEWORD(2, 2);//一些初始的东西 
    WSADATA data;
    if(WSAStartup(sockVersion, &data)!=0)return -2;//创建失败 
    
	SOCKET sclient = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
	if(sclient == INVALID_SOCKET)return -1;//创建失败
	
	sockaddr_in serAddr;//尝试与主机建立连接 
    serAddr.sin_family = AF_INET;
    serAddr.sin_port = htons(8888);
    serAddr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");//主机
	
	if(connect(sclient, (sockaddr *)&serAddr, sizeof(serAddr)) == SOCKET_ERROR)  
	{ 
	    closesocket(sclient);
	    return -3;//连接失败,一般为主机不存在
	    #define HOST_NOT_EXIST (-3)
	}
	
	send(sclient, sendData, strlen(sendData), 0);
	Sleep(DELAY);
	int ret = recv(sclient, recData, recLen, 0);  
    recData[ret] = 0x00;//set EOS
    closesocket(sclient);
    
    WSACleanup();//最后的一些处理 
    
	return 0;//通信成功
	#define CONTRACT_SUC (0)
}

class ServerSocket{//服务端被以类的形式定义 
	WORD sockVersion;    
    WSADATA wsaData;
    SOCKET slisten;
    sockaddr_in sin;
    SOCKET sClient;
    sockaddr_in remoteAddr;
    int nAddrlen;   
    
    public:
    int InitServer(){//启动 
		sockVersion = MAKEWORD(2,2);
		if(WSAStartup(sockVersion, &wsaData)!=0)
			return -1;//fail
		
		slisten = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);    
	    if(slisten == INVALID_SOCKET)    
	        return -2;//socket error  
	    
	    
	    sin.sin_family = AF_INET;//绑定IP和端口  
	    sin.sin_port = htons(8888);
	    sin.sin_addr.S_un.S_addr = INADDR_ANY;// 127.0.0.1
	    if(bind(slisten, (LPSOCKADDR)&sin, sizeof(sin)) == SOCKET_ERROR)    
	        return -3;//bind error
	    
	    if(listen(slisten, 5) == SOCKET_ERROR)//开始监听 
		    return -4;//listen error
		    
	    nAddrlen = sizeof(remoteAddr);//准备循环接收数据 
		return 0;//suc
	}
	int WaitMessage(char* revData,int recLen){
		sClient = accept(slisten, (SOCKADDR *)&remoteAddr, &nAddrlen);//等待连接
		if(sClient == INVALID_SOCKET) return -1;//accept error
		//inet_ntoa(remoteAddr.sin_addr) 接受到的地址的字符串 
		int ret = recv(sClient, revData, recLen, 0);
        revData[ret] = 0x00;//set EOS
	}
	void Feedback(const char* sendData){//反馈一段信息 
        send(sClient, sendData, strlen(sendData), 0);    
        Sleep(DELAY);//try this
        closesocket(sClient);
	}
	void DestructHost(){//结束一个服务器 
		closesocket(slisten);    
    	WSACleanup();    
	}
};

编译的时候要加 -lwsock32 命令。

2018.1.28

//2018.1.28
#include<cstdio>
#include<windows.h>
#pragma comment(lib, "ws2_32.lib")  

int ContractHost(const char* sendData,char* recData,int recLen,const char* DNS){ //给服务器发送信息 这里加了一个参数DNS
	
	WORD sockVersion = MAKEWORD(2, 2);//一些初始的东西 
    WSADATA data;
    if(WSAStartup(sockVersion, &data)!=0)return -2;//创建失败 
    
	SOCKET sclient = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
	if(sclient == INVALID_SOCKET)return -1;//创建失败
	
	sockaddr_in serAddr;//尝试与主机建立连接 
    serAddr.sin_family = AF_INET;
    serAddr.sin_port = htons(8888);
    serAddr.sin_addr.S_un.S_addr = inet_addr(DNS);//主机
	
	if(connect(sclient, (sockaddr *)&serAddr, sizeof(serAddr)) == SOCKET_ERROR)  
	{ 
	    closesocket(sclient);
	    return -3;//连接失败,一般为主机不存在
	    #define HOST_NOT_EXIST (-3)
	}
	
	send(sclient, sendData, strlen(sendData), 0);
	int ret = recv(sclient, recData, recLen, 0);  
    recData[ret] = 0x00;//set EOS
    closesocket(sclient);
    
    WSACleanup();//最后的一些处理 
    
	return 0;//通信成功
	#define CONTRACT_SUC (0)
}

class ServerSocket{//服务端被以类的形式定义 
	WORD sockVersion;    
    WSADATA wsaData;
    SOCKET slisten;
    sockaddr_in sin;
    SOCKET sClient;
    sockaddr_in remoteAddr;
    int nAddrlen;   
    
    public:
    int InitServer(){//启动 
		sockVersion = MAKEWORD(2,2);
		if(WSAStartup(sockVersion, &wsaData)!=0)
			return -1;//fail
		
		slisten = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);    
	    if(slisten == INVALID_SOCKET)    
	        return -2;//socket error  
	    
	    
	    sin.sin_family = AF_INET;//绑定IP和端口  
	    sin.sin_port = htons(8888);
	    sin.sin_addr.S_un.S_addr = INADDR_ANY;// 127.0.0.1
	    if(bind(slisten, (LPSOCKADDR)&sin, sizeof(sin)) == SOCKET_ERROR)    
	        return -3;//bind error
	    
	    if(listen(slisten, 5) == SOCKET_ERROR)//开始监听 
		    return -4;//listen error
		    
	    nAddrlen = sizeof(remoteAddr);//准备循环接收数据 
		return 0;//suc
	}
	int WaitMessage(char* revData,int recLen){
		sClient = accept(slisten, (SOCKADDR *)&remoteAddr, &nAddrlen);//等待连接
		if(sClient == INVALID_SOCKET) return -1;//accept error
		//inet_ntoa(remoteAddr.sin_addr) 接受到的地址的字符串 
		int ret = recv(sClient, revData, recLen, 0);
        revData[ret] = 0x00;//set EOS
	}
	void Feedback(const char* sendData){//反馈一段信息 
        send(sClient, sendData, strlen(sendData), 0);    
        closesocket(sClient);
	}
	void DestructHost(){//结束一个服务器 
		closesocket(slisten);    
    	WSACleanup();    
	}
};

#include<cstdlib>
#include<cstring>
#define clear(A) memset(A,0x00,sizeof(A))
char recData[256];
int main(){
	while(1){
		clear(recData);
		int t=ContractHost("hello world!",recData,255,"192.168.99.151");
		printf("%s\n%d\n",recData,t);
		system("pause");
	}
	return 0;
}

//2018.1.28
#include<cstdio>
#include<windows.h>
#pragma comment(lib, "ws2_32.lib")  

int ContractHost(const char* sendData,char* recData,int recLen,const char* DNS){ //给服务器发送信息 这里加了一个参数DNS
	
	WORD sockVersion = MAKEWORD(2, 2);//一些初始的东西 
    WSADATA data;
    if(WSAStartup(sockVersion, &data)!=0)return -2;//创建失败 
    
	SOCKET sclient = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
	if(sclient == INVALID_SOCKET)return -1;//创建失败
	
	sockaddr_in serAddr;//尝试与主机建立连接 
    serAddr.sin_family = AF_INET;
    serAddr.sin_port = htons(8888);
    serAddr.sin_addr.S_un.S_addr = inet_addr(DNS);//主机
	
	if(connect(sclient, (sockaddr *)&serAddr, sizeof(serAddr)) == SOCKET_ERROR)  
	{ 
	    closesocket(sclient);
	    return -3;//连接失败,一般为主机不存在
	    #define HOST_NOT_EXIST (-3)
	}
	
	send(sclient, sendData, strlen(sendData), 0);
	int ret = recv(sclient, recData, recLen, 0);  
    recData[ret] = 0x00;//set EOS
    closesocket(sclient);
    
    WSACleanup();//最后的一些处理 
    
	return 0;//通信成功
	#define CONTRACT_SUC (0)
}

class ServerSocket{//服务端被以类的形式定义 
	WORD sockVersion;    
    WSADATA wsaData;
    SOCKET slisten;
    sockaddr_in sin;
    SOCKET sClient;
    sockaddr_in remoteAddr;
    int nAddrlen;   
    
    public:
    int InitServer(){//启动 
		sockVersion = MAKEWORD(2,2);
		if(WSAStartup(sockVersion, &wsaData)!=0)
			return -1;//fail
		
		slisten = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);    
	    if(slisten == INVALID_SOCKET)    
	        return -2;//socket error  
	    
	    
	    sin.sin_family = AF_INET;//绑定IP和端口  
	    sin.sin_port = htons(8888);
	    sin.sin_addr.S_un.S_addr = INADDR_ANY;// 127.0.0.1
	    if(bind(slisten, (LPSOCKADDR)&sin, sizeof(sin)) == SOCKET_ERROR)    
	        return -3;//bind error
	    
	    if(listen(slisten, 5) == SOCKET_ERROR)//开始监听 
		    return -4;//listen error
		    
	    nAddrlen = sizeof(remoteAddr);//准备循环接收数据 
		return 0;//suc
	}
	int WaitMessage(char* revData,int recLen){
		sClient = accept(slisten, (SOCKADDR *)&remoteAddr, &nAddrlen);//等待连接
		if(sClient == INVALID_SOCKET) return -1;//accept error
		//inet_ntoa(remoteAddr.sin_addr) 接受到的地址的字符串 
		int ret = recv(sClient, revData, recLen, 0);
        revData[ret] = 0x00;//set EOS
	}
	void Feedback(const char* sendData){//反馈一段信息 
        send(sClient, sendData, strlen(sendData), 0);    
        closesocket(sClient);
	}
	void DestructHost(){//结束一个服务器 
		closesocket(slisten);    
    	WSACleanup();    
	}
};

#include<cstdlib>
#include<cstring>
#define clear(A) memset(A,0x00,sizeof(A))
char recData[256];
int main(){
	while(1){
		clear(recData);
		int t=ContractHost("hello world!",recData,255,"192.168.99.151");
		printf("%s\n%d\n",recData,t);
		system("pause");
	}
	return 0;
}

稍微改了一点点。

//2018.9.24
#include<cstdio>
#include<windows.h>
#pragma comment(lib, "ws2_32.lib")  

int ContractHost(const char* sendData,char* recData,int recLen,const char* DNS, int portnum){ //给服务器发送信息 
	
    WORD sockVersion = MAKEWORD(2, 2);//一些初始的东西 
    WSADATA data;
    if(WSAStartup(sockVersion, &data)!=0)return -2;//创建失败 
    
	SOCKET sclient = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
	if(sclient == INVALID_SOCKET)return -1;//创建失败
	
	sockaddr_in serAddr;//尝试与主机建立连接 
    serAddr.sin_family = AF_INET;
    serAddr.sin_port = htons(portnum);
    serAddr.sin_addr.S_un.S_addr = inet_addr(DNS);//主机
	
	if(connect(sclient, (sockaddr *)&serAddr, sizeof(serAddr)) == SOCKET_ERROR)  
	{ 
	    closesocket(sclient);
	    return -3;//连接失败,一般为主机不存在
	    #define HOST_NOT_EXIST (-3)
	}
	
	send(sclient, sendData, strlen(sendData), 0);
	int ret = recv(sclient, recData, recLen, 0);  
    recData[ret] = 0x00;//set EOS
    closesocket(sclient);
    
    WSACleanup();//最后的一些处理 
    
	return 0;//通信成功
	#define CONTRACT_SUC (0)
}

class ServerSocket{//服务端被以类的形式定义 
	WORD sockVersion;    
    WSADATA wsaData;
    SOCKET slisten;
    sockaddr_in sin;
    SOCKET sClient;
    sockaddr_in remoteAddr;
    int nAddrlen;   
    
    public:
    int InitServer(const char* ipname, int portnum){ //启动  // ipname = 本机IP地址
		sockVersion = MAKEWORD(2,2);
		if(WSAStartup(sockVersion, &wsaData)!=0)
			return -1;//fail
		
		slisten = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);    
	    if(slisten == INVALID_SOCKET)    
	        return -2;//socket error  
	    
	    
	    sin.sin_family = AF_INET;//绑定IP和端口  
	    sin.sin_port = htons(portnum);
	    sin.sin_addr.S_un.S_addr = inet_addr(ipname);
	    if(bind(slisten, (LPSOCKADDR)&sin, sizeof(sin)) == SOCKET_ERROR)    
	        return -3;//bind error
	    
	    if(listen(slisten, 5) == SOCKET_ERROR)//开始监听 
		    return -4;//listen error
		    
	    nAddrlen = sizeof(remoteAddr);//准备循环接收数据 
		return 0;//suc
	}
	const char* WaitMessage(char* revData,int recLen){
		sClient = accept(slisten, (SOCKADDR *)&remoteAddr, &nAddrlen);//等待连接
		if(sClient == INVALID_SOCKET) return (const char *)NULL;//accept error
		//inet_ntoa(remoteAddr.sin_addr) 接受到的地址的字符串 
		int ret = recv(sClient, revData, recLen, 0);
        revData[ret] = 0x00;//set EOS
        return inet_ntoa(remoteAddr.sin_addr);
	}
	void Feedback(const char* sendData){//反馈一段信息 
        send(sClient, sendData, strlen(sendData), 0);    
        closesocket(sClient);
	}
	void DestructHost(){//结束一个服务器 
		closesocket(slisten);    
    	WSACleanup();    
	}
};


//2018.9.24
#include<cstdio>
#include<windows.h>
#pragma comment(lib, "ws2_32.lib")  

int ContractHost(const char* sendData,char* recData,int recLen,const char* DNS, int portnum){ //给服务器发送信息 
	
    WORD sockVersion = MAKEWORD(2, 2);//一些初始的东西 
    WSADATA data;
    if(WSAStartup(sockVersion, &data)!=0)return -2;//创建失败 
    
	SOCKET sclient = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
	if(sclient == INVALID_SOCKET)return -1;//创建失败
	
	sockaddr_in serAddr;//尝试与主机建立连接 
    serAddr.sin_family = AF_INET;
    serAddr.sin_port = htons(portnum);
    serAddr.sin_addr.S_un.S_addr = inet_addr(DNS);//主机
	
	if(connect(sclient, (sockaddr *)&serAddr, sizeof(serAddr)) == SOCKET_ERROR)  
	{ 
	    closesocket(sclient);
	    return -3;//连接失败,一般为主机不存在
	    #define HOST_NOT_EXIST (-3)
	}
	
	send(sclient, sendData, strlen(sendData), 0);
	int ret = recv(sclient, recData, recLen, 0);  
    recData[ret] = 0x00;//set EOS
    closesocket(sclient);
    
    WSACleanup();//最后的一些处理 
    
	return 0;//通信成功
	#define CONTRACT_SUC (0)
}

class ServerSocket{//服务端被以类的形式定义 
	WORD sockVersion;    
    WSADATA wsaData;
    SOCKET slisten;
    sockaddr_in sin;
    SOCKET sClient;
    sockaddr_in remoteAddr;
    int nAddrlen;   
    
    public:
    int InitServer(const char* ipname, int portnum){ //启动  // ipname = 本机IP地址
		sockVersion = MAKEWORD(2,2);
		if(WSAStartup(sockVersion, &wsaData)!=0)
			return -1;//fail
		
		slisten = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);    
	    if(slisten == INVALID_SOCKET)    
	        return -2;//socket error  
	    
	    
	    sin.sin_family = AF_INET;//绑定IP和端口  
	    sin.sin_port = htons(portnum);
	    sin.sin_addr.S_un.S_addr = inet_addr(ipname);
	    if(bind(slisten, (LPSOCKADDR)&sin, sizeof(sin)) == SOCKET_ERROR)    
	        return -3;//bind error
	    
	    if(listen(slisten, 5) == SOCKET_ERROR)//开始监听 
		    return -4;//listen error
		    
	    nAddrlen = sizeof(remoteAddr);//准备循环接收数据 
		return 0;//suc
	}
	const char* WaitMessage(char* revData,int recLen){
		sClient = accept(slisten, (SOCKADDR *)&remoteAddr, &nAddrlen);//等待连接
		if(sClient == INVALID_SOCKET) return (const char *)NULL;//accept error
		//inet_ntoa(remoteAddr.sin_addr) 接受到的地址的字符串 
		int ret = recv(sClient, revData, recLen, 0);
        revData[ret] = 0x00;//set EOS
        return inet_ntoa(remoteAddr.sin_addr);
	}
	void Feedback(const char* sendData){//反馈一段信息 
        send(sClient, sendData, strlen(sendData), 0);    
        closesocket(sClient);
	}
	void DestructHost(){//结束一个服务器 
		closesocket(slisten);    
    	WSACleanup();    
	}
};

又稍微改了一点。