Python基于socket实现简单的即时通讯功能示例

yipeiwu_com5年前Python基础

本文实例讲述了Python基于socket实现简单的即时通讯功能。分享给大家供大家参考,具体如下:

客户端tcpclient.py

# -*- coding: utf-8 -*-
import socket
import threading
# 目标地址IP/URL及端口
target_host = "127.0.0.1"
target_port = 9999
# 创建一个socket对象
client = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
# 连接主机
client.connect((target_host,target_port))
def handle_send():
  while True:
    content = raw_input()
    client.send(content)
def handle_receive():
  while True:
    response = client.recv(4096)
    print response
send_handler = threading.Thread(target=handle_send,args=())
send_handler.start()
receive_handler = threading.Thread(target=handle_receive,args=())
receive_handler.start()

服务器端tcpserver.py

# -*- coding: utf-8 -*-
import socket
import threading
# 监听的IP及端口
bind_ip = "127.0.0.1"
bind_port = 9999
#socket 服务器初始化
server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
server.bind((bind_ip,bind_port))
server.listen(5)
print "[*] Listening on %s:%d" % (bind_ip,bind_port)
# 定义函数handle_client,输入参数client_socket
def handle_client():
  while True:
    request = client_socket.recv(1024)
    print "[*] Received:%s" % request
def handle_send():
  while True:
    content = raw_input()
    client_socket.send(content);
#阻塞在这里,等待接收客户端的数据
client_socket,addr = server.accept()
print "[*] Accept connection from:%s:%d" % (addr[0],addr[1])
#创建一个线程
client_handler = threading.Thread(target=handle_client,args=())
client_handler.start()
send_handler = threading.Thread(target=handle_send,args=())
send_handler.start()

更多关于Python相关内容可查看本站专题:《Python Socket编程技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总

希望本文所述对大家Python程序设计有所帮助。

相关文章

Python计算已经过去多少个周末的方法

本文实例讲述了Python计算已经过去多少个周末的方法。分享给大家供大家参考。具体如下: def weekends_between(d1,d2): days_between =...

python批量读取txt文件为DataFrame的方法

python批量读取txt文件为DataFrame的方法

我们有时候会批量处理同一个文件夹下的文件,并且希望读取到一个文件里面便于我们计算操作。比方我有下图一系列的txt文件,我该如何把它们写入一个txt文件中并且读取为DataFrame格式呢...

qpython3 读取安卓lastpass Cookies

之前我的博客写了python读取windows chrome Cookies,沿着同样的思路,这次本来想尝试读取安卓chrome Cookies, 但是可能是chrome的sqlite3...

解决python3 json数据包含中文的读写问题

python3 默认的是UTF-8格式,但在在用dump写入的时候仍然要注意:如下 import json data1 = { "TestId": "testcase001",...

Python对文件操作知识汇总

打开文件 操作文件 1打开文件时,需要指定文件路径和打开方式 打开方式: r:只读 w:只写 a:追加 “+”表示可以同时读写某个文件 r+:读写 w+:写读 a+:同a U"表示在读取...