socket编程-微软小兵
socket两端建立连接,不断开的连接的情况下做数据交互,客户端发送数据和服务端返回数据。直到客户端要求断开,则关闭连接。
代码目录结构:
aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQoAAACiCAIAAAA2kRSpAAAQ6UlEQVR4nO2d/5MT5R3H97/oL84otqA92o7fpl8y1lh1WmWkdmzPOUYtom0Ubw5xHHtzwkwKFUQQJ4AjFvByqDCAIgLjIoOwgtzRowPjWQuWU8PXwn2Dcsdd7pLsfvrD5pJnd59ns7nL3j6be79mf0g2u5vd5HnleZ7keedRdF3XdZ0AAA4U6AGACOgBgBCOHgaRQaQblDMoZ5BukG7kV46BmlqlZptSs0357JvPKnLGAEwYXmuPsblBRDXbFNsNAMJCCT0MopxBGZ1GdMrolDPK9qQCtUdnIqJEEp1EpMaUmDq6yrwFgH+46aEbNKLTYM7ozxr9WWMgawzljIyrHx3bm8ylsKZmm9IwNz6uc4QeICCEeugGDevUnzX6RoyuYf1SWu8e1v+XMYZyQj+++KBoRcf2psZ5CxrnLajZppg3zGV8Z+uuB5wBFYavh0E0olN/1uge1s8O6d9d09/7b3bOiZGuYf1q1q5H47yFjfMWNs5bkOlqznQ1D6Xe7O1YQUSN8xbQ1UO9HSssN8YF9AATCl+PjE4DWaN7WD89qH/dn1t/LjOlNX3d4fS5If3yiF2PhrnxJav+QVcPWZYL7zXOW9DbsaJje1PD3Lh5Q6CHGlMiCTURURRFUWIqkRpTFEVR8i0qptjz9OhMRBRFicXy+xR3U2O2FYWNC08EgCscPXIGpXPG5RHj3JD+dX/u72czN7Sm//pd9rrD6dODeq9DDyJ69ImXqWc3uxRaUw1z4+ZSuOvYW40VirBZpG0KuOihxpjCz9YeaoyzvjMRG12nxiAIKAlHj6xB17JG97CeGtQ3nMu7sTiV16OPpwcRpVJaMh5NpTQiogvvmbWH2aZqmBt3bVyxRZl3W6RHzFbEGT2KNYe9AkH9AbzD0SOjU3/WuDSsv3shO2XUDVOP80P6FcFXV1oySqloMh4lopm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7vKfrbBvvJ8dfNriw+KDFdjSow8EHDW3KmBaOHt7T32LariRwulvXSI/qXBVQ9bx6N0O4ItcWyX2HkUfy+E1xB09kXsZxvkK8//e4DCA9Z7nM06E5EIeSDgrPk43KByYt9jeJMKb7NnPSwFyKsf7BvGDbz7fSH8ThKvp24920BfeeGr69BDuFnQtYeXrLmHFpQL3mPfpd4kZxXPr51L6mFp39r+RSWS6LS3E4qHFBzc3wsRtheF/05RPNsgXnlrk8zx9wD5fZir4m9mnpTzqp0E/M1VydrDde8yYt+dhTnLhSVe3EH0qoeje+s8pL1AsiVV/Hno04XY2x6Ozo8di1cBvPLsiTGt0WJnxWmvYzPe+yQk+N89RHoQkSc9pIp9l/8FqNs1EJFE34YSWX4IkeyVL4My3iQpfjUXVRpj16NkofON8p/Z9aMsuAsRYJ6tjK+8R8qyVwo9iGeIh64I/61QqyX2LfGFVPkrX0AWPQCQEOgBgBDoAYCQvB4AACf/B/ufNmAlTmjUAAAAAElFTkSuQmCC" alt="" />
__init__.py :空
models.py:
#!/usr/bin/env python
#coding:utf-8 from sqlhelper import MySqlHelper class UserInfo: def __init__(self):
self.sqlHelper = MySqlHelper() def CheckLogin(self,name,pwd):
'''验证用户名是否合法
@param name:用户名
@param pwd:密码
@return: 如果登录成功,返回该用户的自增ID;否则,返回False
'''
sql = '''select Nid,Name,Password from UserInfo where Name=%s and Password = %s'''
params = (name,pwd,)
result = self.sqlHelper.GetSimple(sql, params)
if not result:
return False
else:
return result['Nid'] class ChatRecord: def __init__(self):
self.sqlHelper = MySqlHelper() def InsertRecord(self,message,date,userid):
'''插入聊天记录
@param message:聊天信息
@param date:时间
@param userid:用户ID
@return: 如果聊天记录插入成功,返回True;否则返回False
'''
sql = '''insert into ChatRecord(Message,Date,UserId) values(%s,%s,%s)'''
params = (message,date,userid,)
result = self.sqlHelper.InsSample(sql, params) #插入聊天记录,返回受影响条数,如果受影响条数为 1,表示插入成功
if result != 1:
return False
else:
return True def GetRecord(self,userid):
'''获取聊天记录
@param userid:用户ID
@return: 所有聊天记录
'''
sql = ''' select Message,Date from ChatRecord where UserId=%s '''
params = (userid,)
result = self.sqlHelper.GetDict(sql, params)#根据用户ID,获取该用户的所有聊天记录
print result
if not result:
return False
else:
return result
sqlhelper.py:
#!/usr/bin/env python
#coding:utf-8 import MySQLdb
import _mysql_exceptions class MySqlHelper: def __init__(self):
self.__connDict = {'host':'127.0.0.1','user':'root','passwd':'1234','db':'milkteaDB'} def GetSimple(self,sql,params):
'''获取单条数据
@param sql:sql语句
@param params:参数
@return: 数据
'''
conn = MySQLdb.connect(**self.__connDict)
cur = conn.cursor(cursorclass = MySQLdb.cursors.DictCursor)
cur.execute(sql,params)
data = cur.fetchone()
cur.close()
conn.close()
return data def GetDict(self,sql,params):
'''获取多条数据(字典类型)'''
conn = MySQLdb.connect(**self.__connDict)
cur = conn.cursor(cursorclass = MySQLdb.cursors.DictCursor)
cur.execute(sql,params)
data = cur.fetchall()
cur.close()
conn.close()
return data def InsSample(self,sql,params):
'''插入单条数据
@return: 受影响的条数
'''
conn = MySQLdb.connect(**self.__connDict)
cur = conn.cursor(cursorclass = MySQLdb.cursors.DictCursor)
count = cur.execute(sql,params)
conn.commit()
cur.close()
conn.close()
return count def InsSample_ReturnId(self,sql,params):
'''插入单条数据
@return: 返回自增ID
'''
conn = MySQLdb.connect(**self.__connDict)
cur = conn.cursor(cursorclass = MySQLdb.cursors.DictCursor)
cur.execute(sql,params)
id = cur.lastrowid
conn.commit()
cur.close()
conn.close()
return id
client.py
#!/usr/bin/env python
#coding:GBK import socket
import sys
import json ip_port = ('127.0.0.1',9998)
sk = socket.socket()
sk.connect(ip_port) container = {'key':'','data':''}
while True:
data = sk.recv(1024)
rev_data = json.loads(data)
print rev_data['data']
if not rev_data['key']:
user = raw_input('username:')
pwd = raw_input('password:')
rev_data['data']=[user,pwd]
sk.sendall(json.dumps(rev_data))
else:
inp = raw_input('reply:')
rev_data['data'] = inp
sk.sendall(json.dumps(rev_data))
if inp == 'exit':
break
sk.close()
server.py:
#!/usr/bin/env python
#coding:utf-8 import SocketServer
import json
import time
from backend.models import UserInfo,ChatRecord class MyServer(SocketServer.BaseRequestHandler): def setup(self):
pass def handle(self):
#userinfo = UserInfo() #实例化一个用户表操作类
#chatrecord = ChatRecord() #实例化一个记录表操作类 container = {'key':'','data':''}
container['data'] = 'ok...' conn = self.request
conn.sendall(json.dumps(container))
Flag = True
while Flag:
try:
data = conn.recv(1024)
print data
rev_data = json.loads(data)
if rev_data['data'] == 'exit':
conn.close()
break
#如果key为空,则表示用户没有登录或登录失败
if not rev_data['key']:
name,pwd = rev_data['data']
#re = userinfo.CheckLogin(name, pwd)
re = 1
if re:
rev_data['key'] = re
rev_data['data'] = '约吗?'
else:
rev_data['data'] = 'failed.'
conn.sendall(json.dumps(rev_data))
#用户已经登录
else:
datetime = time.strftime('%Y-%m-%d %H:%M:%S') if rev_data['data']=='list': #聊天记录
#rev_data['data'] = chatrecord.GetRecord(rev_data['key'])
pass elif rev_data['data'].__contains__('yes'):
#如果用户输入的是yes,那么就把用户输入的记录保存到数据
#chatrecord.InsertRecord(rev_data['data'], datetime, rev_data['key'])
rev_data['data'] = 'I am gay.'
#把聊天机器人的回复也保存到数据库
#chatrecord.InsertRecord(rev_data['data'], datetime, rev_data['key'])
else:
#如果用户输入的不是yes,把用户输入的记录保存到数据
#chatrecord.InsertRecord(rev_data['data'], datetime, rev_data['key'])
rev_data['data'] = 'what?'
#把聊天机器人的回复也保存到数据库
#chatrecord.InsertRecord(rev_data['data'], datetime, rev_data['key'])
conn.sendall(json.dumps(rev_data))
except Exception,e:
print e
Flag = False
def finish(self):
pass if __name__ == '__main__':
server = SocketServer.ThreadingTCPServer(('127.0.0.1',9998),MyServer)
server.serve_forever()
socket编程-微软小兵的更多相关文章
- linux tcp/ip编程和windows tcp/ip编程差别以及windows socket编程详解
最近要涉及对接现有应用visual c++开发的tcp客户端,花时间了解了下windows下tcp开发和linux的差别,从开发的角度而言,最大的差别是头文件(早期为了推广尽可能兼容,后面越来越扩展, ...
- win32下Socket编程(转载)
在网上找了很多的资料,现将这些资料整合起来,详细介绍一下VC下的socket编程,并提供一个服务器客户端具体的实例.希望对您有所帮助 一.原理部分 (个人觉得这篇写的可以,所以转与此,原文地址:htt ...
- Windows Socket和Linux Socket编程的区别 ZZ
socket相关程序从Windows移植到Linux下需要注意的: 1)头文件 Windows下winsock.h/winsock2.h Linux下sys/socket.h 错误处理:errno.h ...
- socket编程之中的一个:计算机网络基础
在開始学习网络之前先复习下计算机网络基础吧. 鲁迅说,天下文章一大抄.看你会炒不会炒,基础知识就抄抄书吧. 一 分层模型 1 为什么分层 为了简化网络设计的复杂性.通讯协议採用分层结构.各层协议之间既 ...
- Socket编程模型之完毕port模型
转载请注明来源:viewmode=contents">http://blog.csdn.net/caoshiying?viewmode=contents 一.回想重叠IO模型 用完毕例 ...
- 记一次:Windows的Socket编程学习和分析过程
Socket编程依赖于:WS2_32.dll --- 服务端 --- .导入我们需要的函数 #incldue <windows.h> //#include<WinSock2.h> ...
- C++/C socket编程
目录 socket()函数 何为socket Internet套接字 流格式套接字SOCK_STREAM 数据报格式套接字SOCK_DGRAM TCP/IP协议族 创建套接字 加载套接字库 Windo ...
- Linux下的C Socket编程 -- server端的继续研究
Linux下的C Socket编程(四) 延长server的生命周期 在前面的一个个例子中,server在处理完一个连接后便会立即结束掉自己,然而这种server并不科学啊,server应该是能够一直 ...
- java socket编程(li)
一.网络编程中两个主要的问题 一个是如何准确的定位网络上一台或多台主机,另一个就是找到主机后如何可靠高效的进行数据传输.在TCP/IP协议中IP层主要负责网络主机的定位,数据传输的路由,由IP地址可以 ...
随机推荐
- bat文件设置环境变量
::获取管理员权限 @echo off%1 mshta vbscript:CreateObject("Shell.Application").ShellExecute(" ...
- JSONPath - XPath for JSON
http://goessner.net/articles/JsonPath/ [edit] [comment] [remove] |2007-02-21| e1 # JSONPath - XPath ...
- CPP-基础:虚函数表
虚函数表 对C++ 了解的人都应该知道虚函数(Virtual Function)是通过一张虚函数表(Virtual Table)来实现的.简称为V-Table.在这个表中,主是要一个类的虚函数的地址表 ...
- 通过存储过程批量生成spool语句
过存储过程批量生成spool语句 CREATE OR REPLACE PROCEDURE pro_yx_full_txt IS export_handle UTL_FILE.file_type; v_ ...
- PAT (Basic Level) Practise (中文)- 1015. 德才论 (25)
http://www.patest.cn/contests/pat-b-practise/1015 宋代史学家司马光在<资治通鉴>中有一段著名的“德才论”:“是故才德全尽谓之圣人,才德兼亡 ...
- Bootstrap标签页(Tab)插件
标签页(Tab)在Bootstrap导航元素一章中简介过,通过结合一些data属性,您可以轻松地创建一些标签页界面.通过这个插件您可以把内容放置在标签页或胶囊式标签页甚至是下拉菜单标签页中. 用法 您 ...
- Nginx超时配置
Nginx超时配置 1.client_header_timeout 语法client_header_timeout time 默认值60s 上下文http server 说明 指定等待client发送 ...
- c++ 调用php
int _System(const char * cmd, std::string& strRet) { FILE * fp; char * p = NULL; ; if ((fp = _po ...
- JavaScript数组之傻傻分不清系列(split,splice,slice)
因业务场景需求,需要将一个数组截断而不需要影响原数组.这里来理解一下 slice,splice,split slice() 从某个已有的数组返回选定的元素.(JavaScript Array 对象) ...
- 【二分 最大流】bzoj1532: [POI2005]Kos-Dicing
晚上果然不适合调题目 Description Dicing 是一个两人玩的游戏,这个游戏在Byteotia非常流行. 甚至人们专门成立了这个游戏的一个俱乐部. 俱乐部的人时常在一起玩这个游戏然后评选出 ...