python-socket作业
#客户端
import socket
import threading
import tkinter
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('localhost', 5550))
flag = False
class Connection:
def __init__(self):
self.win = tkinter.Tk() # 创建主窗口
self.win.title('登陆界面')
self.win.geometry("400x400+200+20")
self.labelName = tkinter.Label(self.win, text='账号').grid(row=0, column=0)
self.labelPasswd = tkinter.Label(self.win, text='密码').grid(row=2, column=0)
self.name = tkinter.Variable()
self.word = tkinter.Variable()
self.entryName = tkinter.Entry(self.win, textvariable=self.name).grid(row=0, column=1)
self.entryPasswd = tkinter.Entry(self.win, show='*',width =20,textvariable= self.word).grid(row=2, column=1)
self.text = tkinter.Text(self.win, height=10, width=20)
self.text.grid(row=5, column=1)
self.labeltext = tkinter.Label(self.win, text='消息').grid(row=5, column=0)
self.button1 = tkinter.Button(self.win, text="连接", command=self.connect).grid(row=8, column=1)
self.win.mainloop()
def connect(self):
username = self.name.get()
password = self.word.get()
userinfo = username + '$' + password
sock.send(userinfo.encode())
info = sock.recv(1024).decode()
if info == '0':
printStr = "账号或密码失败\n"
self.text.insert(tkinter.INSERT, printStr)
return
else:
printStr = "welcome to server!\n"
self.text.insert(tkinter.INSERT, printStr)
global flag
flag = True
self.win.destroy() #连接成功关闭窗体
class Communicate:
def __init__(self):
self.win = tkinter.Tk() # 创建主窗口
self.win.title('聊天室')
self.win.geometry("400x300+200+20")
self.mesg = tkinter.Variable() # 发送的信息
self.labelmesg = tkinter.Label(self.win, text='说话').grid(row=4, column=0)
self.entrymesg = tkinter.Entry(self.win, textvariable=self.mesg).grid(row=4, column=1)
self.text = tkinter.Text(self.win, height=10, width=40)
self.text.grid(row=5, column=1)
self.labeltext = tkinter.Label(self.win, text='消息').grid(row=5, column=0)
button2 = tkinter.Button(self.win, text="发送", command=self.sendThreadFunc).grid(row=8, column=2)
th2 = threading.Thread(target=self.recvThreadFunc)
th2.setDaemon(True)
th2.start()
self.win.mainloop()
def sendThreadFunc(self):
try:
myword = self.mesg.get()
self.mesg.set('')
sock.send(myword.encode())
if myword =='exit':
printStr = "你的聊天结束\n"
self.text.insert(tkinter.INSERT, printStr)
sock.close()
except ConnectionAbortedError:
printStr = "服务器终止了连接\n"
self.text.insert(tkinter.INSERT, printStr)
sock.close()
except ConnectionResetError:
printStr = "服务器崩了\n"
self.text.insert(tkinter.INSERT, printStr)
sock.close()
def recvThreadFunc(self):
while True:
try:
otherword = sock.recv(1024).decode()
otherword = otherword +'\n'
if otherword:
self.text.insert(tkinter.INSERT, otherword)
else:
pass
except ConnectionAbortedError:
printStr = "服务器终止了连接\n"
self.text.insert(tkinter.INSERT, printStr)
sock.close()
break
except ConnectionResetError:
printStr = "服务器崩了\n"
self.text.insert(tkinter.INSERT, printStr)
sock.close()
break
def shut_down(self):
self.win.destroy()
#--------------------------用户窗体
if __name__ =='__main__':
deng = Connection()
if flag :
liao = Communicate()
#服务器端
import socket
import threading
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(('localhost', 5550))
sock.listen(5)
print('Server', socket.gethostbyname('localhost'), 'listening ...')
mydict = dict()
mylist = list()
account = {'123':'123','456':'456','root':'xiuwenL'}
name = ['123','456','789']
# 把whatToSay传给除了exceptNum的所有人
def tellOthers(exceptNum, whatToSay):
for c in mylist:
#if c.fileno() != exceptNum:
try:
c.send(whatToSay.encode())
except:
pass
def subThreadIn(myconnection, connNumber,nickname):
#nickname = myconnection.recv(1024).decode()
mydict[myconnection.fileno()] = nickname
mylist.append(myconnection)
print('connection', connNumber, ' has nickname :', nickname)
tellOthers(connNumber, '【系统提示:' + mydict[connNumber] + ' 进入聊天室】')
while True:
try:
recvedMsg = myconnection.recv(1024).decode()
if recvedMsg:
if recvedMsg =='exit': #用户退出
mylist.remove(myconnection)
print(mydict[connNumber], 'exit, ', len(mylist), ' person left')
tellOthers(connNumber, '【系统提示:' + mydict[connNumber] + ' 离开聊天室】')
myconnection.close()
return
print(mydict[connNumber], ':', recvedMsg)
tellOthers(connNumber, mydict[connNumber] + ' :' + recvedMsg)
except (OSError, ConnectionResetError):
try:
mylist.remove(myconnection)
except:
pass
print(mydict[connNumber], 'exit, ', len(mylist), ' person left')
tellOthers(connNumber, '【系统提示:' + mydict[connNumber] + ' 离开聊天室】')
myconnection.close()
return
while True:
connection, addr = sock.accept()
while True:
try:
# connection.settimeout(5)
suc = False
buf = connection.recv(1024).decode()
buf = buf.split('$')
if buf[0] in account.keys() and buf[1] in account.values() :
print('Accept a new connection', connection.getsockname(), connection.fileno())
connection.send(b'1')
suc = True
else:
connection.send(b'0')
if suc : #只有登陆成功才加入线程
# 为当前连接开辟一个新的线程
mythread = threading.Thread(target=subThreadIn, args=(connection, connection.fileno(),buf[0]))
mythread.setDaemon(True)
mythread.start()
break
except:
connection.close()
python-socket作业的更多相关文章
- Python Socket 编程——聊天室示例程序
上一篇 我们学习了简单的 Python TCP Socket 编程,通过分别写服务端和客户端的代码了解基本的 Python Socket 编程模型.本文再通过一个例子来加强一下对 Socket 编程的 ...
- Python Socket 网络编程
Socket 是进程间通信的一种方式,它与其他进程间通信的一个主要不同是:它能实现不同主机间的进程间通信,我们网络上各种各样的服务大多都是基于 Socket 来完成通信的,例如我们每天浏览网页.QQ ...
- python socket发送魔法包网络唤醒开机.py
python socket发送魔法包网络唤醒开机.py 现在的电脑应该都普遍支持有线网络的WOL了,支持无线网络唤醒的电脑,可能比较少. """ python socke ...
- Python socket编程之二:【struct.pack】&【struct.unpack】
import struct """通过 socket 的 send 和 recv 只能传输 str 格式的数据""" "" ...
- Python Socket,How to Create Socket Server? - 网络编程实例
文章出自:Python socket – network programming tutorial by Silver Moon 原创译文,如有版权问题请联系删除. Network programin ...
- Python Socket,How to Create Socket Cilent? - 网络编程实例
文章出自:Python socket – network programming tutorial by Silver Moon 原创译文,如有版权问题请联系删除. Network programin ...
- Python Socket通信原理
[Python之旅]第五篇(一):Python Socket通信原理 python Socket 通信理论 socket例子 摘要: 只要和网络服务涉及的,就离不开Socket以及Socket编 ...
- Python Socket单线程+阻塞模式
Python之旅]第五篇(二):Python Socket单线程+阻塞模式 python Socket单线程 Socket阻塞模式 串行发送 摘要: 前面第五篇(一)中的一个Socket例子其实就是 ...
- python socket之tcp服务器与客户端demo
python socket之tcp服务器与客户端demo 作者:vpoet mails:vpoet_sir@163.com server: # -*- coding: cp936 -*- ''' 建立 ...
- python socket编程---从使用Python开发一个Socket示例说到开发者的思维和习惯问题
今天主要说的是一个开发者的思维和习惯问题. 思维包括编程的思维和解决一个具体问题的分析思维,分析思路,分析方法,甚至是分析工具. 无论是好习惯还是不好的习惯,都是在者一天一天的思维中形成的.那些不好的 ...
随机推荐
- hdu 3085(双向bfs)
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=3085 思路:双向广搜,每次从M出发,搜三步,从G出发,搜一步,然后就是判断是否走到对方已经走过的格子, ...
- CSS解决图片缩小不变形
我会在图片上加: <img style="max-width:80px;max-height:80px;"> 限制其最大宽度和高度
- 移动端form表单
始终绑定submit事件 不单独的对[提交]按钮绑定click事件,对整个表单绑定submit提交事件,这样可以让整个表单内的文本框获得Enter提交的VIP待遇,并且在移动端中可以让文本框聚焦时键盘 ...
- oracle怎么把一个用户下的表复制给另一个用户?(授予表权限)
//把system读写权限 授权给scottselect 'Grant all on '||table_name||' to scott;' from all_tables where owner = ...
- 基于Consul+Upsync+Nginx实现动态负载均衡
基于Consul+Upsync+Nginx实现动态负载均衡 1.Consul环境搭建 下载consul_0.7.5_linux_amd64.zip到/usr/local/src目录 cd /usr/l ...
- 160229-01、web页面常用功能js实现
web页面常用功能js实现 1.网页未加载时弹出新窗口 <body onunload="window.open('http://www.a68.cn');">< ...
- MongoDB 使用 ObjectId 代替时间
An ObjectId is a 12-byte unique identifier consisting of: a 4-byte value representing the seconds si ...
- netstat -tulpn
[root@d java]# netstat -tulpnActive Internet connections (only servers)Proto Recv-Q Send-Q Local Add ...
- wcur LOCATE +
w字符串处理 DROP PROCEDURE IF EXISTS w_unique; DELIMITER /w/ CREATE PROCEDURE w_unique() BEGIN DECLARE do ...
- 剖析Docker文件系统:Aufs与Devicemapper
http://www.infoq.com/cn/articles/analysis-of-docker-file-system-aufs-and-devicemapper Docker镜像 典型的Li ...