服务端:
server:
from Tkinter import *
import socket;
import threading
import time
”’
这是一个聊天小程序
”’
topWv = Tk();
topWv.title(“connect”)
topWv.geometry(‘500x800’)
server=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
server.bind((‘localhost’, 20000))
server.listen(5)
tcpSock=None;
addr=None;
message_var = StringVar();#这个变量存放文本框中的值
message_e=Entry(topWv,textvariable=message_var);
message_var.set(“hello”)
message_e.place(x=10,y=740,anchor=NW)
def send():
”’点击发送按钮”’
global server;
global message_var
message_str = ”.join(message_var.get());
print message_str
global tcpSock;
global addr;
tcpSock.send(message_str);
pass
sendBtn= Button(topWv,text=”发送”,bg=”green”,width=10,height=1,command=send);
sendBtn.place(x=250,y=730,anchor=NW);
t=Text(topWv,width=50,height=35);
t.place(x=10,y=100,anchor=NW)
def server_thread():
global server;
global tcpSock;
global addr;
global t;
tcpSock, addr = server.accept();
while 1:
print “wait data”
data=tcpSock.recv(1024)
print addr
if not data:
continue;
else:
print data;
t=threading.Thread(target=server_thread,args=());
t.start();
topWv.mainloop();
客户端
client:
from Tkinter import *
from socket import *
import threading
import time
”’
这是一个聊天小程序
”’
topWv = Tk();
topWv.title(“connect”)
topWv.geometry(‘500x800’)
message_var = StringVar();#这个变量存放文本框中的值
message_e=Entry(topWv,textvariable=message_var);
message_var.set(“hello”)
message_e.place(x=10,y=740,anchor=NW)
print ‘开始链接服务器’
client = socket(AF_INET, SOCK_STREAM);
client.connect((‘localhost’, 20000));
print ‘链接成功’
def okBtn():
”’点击确定按钮,是点击按钮确定链接服务器”’
print var.get()
return;
def cancleBtn():
”’点击取消按钮,点击取消按钮,界面消失”’
print “click cancleBtn”;
return;
def send():
”’点击发送按钮”’
global client;
global message_var;
message_str =”.join(message_var.get());
print message_str
client.send(message_str)
pass
okBtn=Button(topWv,text=”链接”,bg=”green”,command=okBtn);
cancleBtn=Button(topWv,text=”取消”,bg=”red”,command=cancleBtn)
sendBtn= Button(topWv,text=”发送”,bg=”green”,width=10,height=1,command=send);
okBtn.place(x=400,y=10,anchor=NW);
cancleBtn.place(x=400,y=60,anchor=NW);
sendBtn.place(x=250,y=730,anchor=NW);
linkLable=Label(topWv,text=”请输入服务器ip地址”,bg=”white”,font=”Arial”,width=20,height=1);
linkLable.place(x=10,y=20,anchor=NW);
var = StringVar();#这个变量存放文本框中的值
e=Entry(topWv,textvariable=var);
var.set(“127.0.0.1”);
e.place(x=10,y=50,anchor=NW);
t=Text(topWv,width=50,height=35);
t.place(x=10,y=100,anchor=NW)
def client_thread():
global t;
while 1:
global client;
data= client.recv(1024)
if not data:
break
else:
t.insert(data)
t.insert(INSERT,data)
print data
t=threading.Thread(target=client_thread,args=());
t.start();
topWv.mainloop();
因为是初学,所以有点写的不太好,见笑了