一、会躲的窗口
很多年前就有这样的整人程序了,用MFC写毫不为难,拿来做wxPython的练习而已。
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import wx
import random
class DodgeFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, -1, 'Bling bling',
size=(300, 100))
panel = wx.Panel(self, -1)
self.SetCursor(wx.StockCursor(wx.CURSOR_HAND))
self.button = wx.Button(panel, -1, "Click on me", pos=(50, 20))
self.Bind(wx.EVT_BUTTON, self.OnClick, self.button)
self.button.Bind(wx.EVT_ENTER_WINDOW, self.OnEnterWindow)
def OnClick(self, event):
self.Destroy()
event.Skip()
def OnEnterWindow(self, event):
self.Move(wx.Point(random.randint(0, 1000), random.randint(0, 500)))
event.Skip()
if __name__ == '__main__':
app = wx.PySimpleApp()
frame = DodgeFrame()
frame.Show()
app.MainLoop()
二、简单的Socket通信
命令行下的Socket通信,仅对本机(修改localhost为手动输入的IP即可进行网络通信)。Client端发送消息,Server端做出响应。
注意Server必须接受Client端发来的‘exit’指令才会退出。
Server端:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import socket
if __name__ == '__main__':
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(('localhost', 8001))
sock.listen(5)
except socket.error:
print 'Socket Failed!'
sys.exit()
clientExit=False
serverExit=False
print 'Server running'
while not serverExit:
connection,address = sock.accept()
print 'Client log in'
while not clientExit:
try:
connection.settimeout(10)
buf = connection.recv(1024)
if buf == 'Hello' or buf == 'hello':
connection.send('Welcome to server!')
print '~@Client: %s' % buf
elif buf == 'Goodbye' or buf == 'goodbye':
clientExit = True
elif buf == 'Exit' or buf == 'exit':
clientExit = True
serverExit = True
else:
connection.send('Where is your manner?')
print '~@Client: %s' % buf
except socket.timeout:
print 'Time out'
clientExit = True
connection.close()
print 'Client log out'
clientExit=False
print 'Server exit'
Client端:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import socket
import sys
if __name__ == '__main__':
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('localhost', 8001))
except socket.error:
print 'Socket Failed!'
sys.exit()
x=raw_input('->')
while x != 'exit' and x != 'goodbye' and x != 'Exit' and x != 'Goodbye':
try:
sock.send(x)
print '~@Server: %s' % sock.recv(1024)
x=raw_input('->')
except:
print 'Server offline'
sock.close()
sys.exit()
sock.send(x)
sock.close()
print 'Client exit'