一、主界面程序,文件名socketTester.py
from tkinter import *
import tkinter.messagebox as messagebox
import socketClient1
class socketTester():
def __init__(self):
master = Tk()
master.geometry("640×480")
master.title("socket测试工具")
frame1 = Frame(master)
frame1.pack(fill=X)
#host
lbHost = Label(frame1, text='host')
lbHost.grid(row=1,column=0)
# 输入框 (Entry)
self.host = StringVar()
eHost = Entry(frame1, textvariable=self.host)
self.host.set("localhost")
eHost.grid(row=1, column=1)
#port
lbPort = Label(frame1, text='port')
lbPort.grid(row=2,column=0)
# 输入框 (Entry)
self.port = StringVar()
ePort = Entry(frame1, textvariable=self.port)
self.port.set("10021")
ePort.grid(row=2, column=1)
# 按钮 (Button)
btnGetHost = Button(frame1, text='连接', command=self.getHost)
btnGetHost.grid(row=3, column=1)
frameMsg = Frame(master)
frameMsg.pack(fill=X)
self.result = StringVar()
self.result.set("等待连接")
lbResult = Label(frameMsg, textvariable=self.result, font='15', bg='white', fg='red')
lbResult.grid(row=2)
#待发送的消息
lbSendMsg = Label(frameMsg, text='待发送的消息:')
lbSendMsg.grid(row=1,column=0)
# 输入框 (Entry)
self.sendMsg = StringVar()
eSendMsg = Entry(frameMsg, textvariable=self.sendMsg)
self.sendMsg.set("hello")
eSendMsg.grid(row=1, column=1)
# 按钮 (Button)
btnSendMsg = Button(frameMsg, text='发送', command=self.sendMsgg)
btnSendMsg.grid(row=1, column=2)
master.mainloop()
def getHost(self):
print(self.host.get() + ":" + self.port.get())
result1 = socketClient1.connect(self.host.get(),self.port.get())
#messagebox.showinfo("连接结果",result1)
self.result.set(result1)
def sendMsgg(self):
self.result.set(self.result.get()+"\n" + socketClient1.sendMsg1(self.sendMsg.get()))
socketTester()
二、主逻辑,文件名socketClient1.py
import socket
import sys
obj = socket.socket()
def connect(host,port):
print("connecting " + host +":" + port)
obj.connect((host,int(port)))
result = "connect server success"
print(result)
return result
def sendMsg1(msg):
print("msn: " + msg )
if msg== "bye" :
obj.close();
sys.exit(0);
else :
print("sending msg:" + msg)
obj.send(msg.encode())
ret = str(obj.recv(1024),encoding="utf-8")
receiveMsg = "receive msg from server:" + ret
print("receive msg from server:" + ret)
return receiveMsg
三、模拟的服务器
#!/usr/bin/python3
import socket
s = socket.socket()
host = "localhost"
port = 10021
path = "host:"+ host +",port:" + str(port)
print(path)
s.bind((host, port))
s.listen(5)
c, addr = s.accept()
while True:
c.send(b'Thank you for connecting')
data = c.recv(1024)
if data:
if data == "bye" :
sys.exit(1)
else :
print(addr ,":", data)
# c.close()