xml地图|网站地图|网站标签 [设为首页] [加入收藏]

智能家电

当前位置:美高梅游戏网站 > 智能家电 > 小小聊天室Python代码实现,聊天室python代码

小小聊天室Python代码实现,聊天室python代码

来源:http://www.gd-chuangmei.com 作者:美高梅游戏网站 时间:2019-09-02 20:42

小小聊天室Python代码实现,聊天室python代码

相对于Java方式的聊天室,Python同样可以做得到。而且可以做的更加的优雅。想必少了那么多的各种流的Python Socket,你一定会喜欢的。
至于知识点相关的内容,这里就不多说了。

UDP方式

服务器端

# coding:utf-8

#  __author__ = 'Mark sinoberg'
#  __date__ = '2016/7/7'
#  __Desc__ = 创建一个简单的套接字监听请求

import socket

HOST = '192.168.59.255'
PORT = 9998

s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
s.bind(('',PORT))
print '套接字已启动!'
while True:
  data,addr = s.recvfrom(1024)
  print addr,str(' : ')+data

客户端

# coding:utf-8

#  __author__ = 'Mark sinoberg'
#  __date__ = '2016/7/7'
#  __Desc__ = socket的客户端的简单实现

import socket

PORT = 9998
HOST = '192.168.59.255'
s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
words = raw_input('Client:')
while words != 'quit':
  s.sendto(words,(HOST,PORT))
  words = raw_input('Client:')
s.close()

是不是很简单啊。我们需要注意的就是socket的第二个参数为SOCK_DGRAM。因为这和TCP方式的SOCK_STREAM 有所不同。

TCP方式

服务器端

# coding:utf-8

#  __author__ = 'Mark sinoberg'
#  __date__ = '2016/7/7'
#  __Desc__ = 简单的tcpsocket的实现

from socket import *
from time import ctime

HOST = ''
PORT = 9999
BUFFERSIZE = 1024
ADDRESS = (HOST,PORT)

s = socket(AF_INET,SOCK_STREAM)
s.bind(ADDRESS)
s.listen(5)

while True:
  print 'Waiting for clients cennect!'
  tcpclient,addr = s.accept()
  print 'Connected By ',addr

  while True:
    try:
      data = tcpclient.recv(BUFFERSIZE)
    except Exception,e:
      print e.message
      tcpclient.close()
      break
    if not data:
      print "No Data received!"
      break
    senddata = 'Hi,you send me:[%s]%s'%(ctime(),data.encode('utf8'))
    tcpclient.send(senddata.encode('utf8'))
    print addr,' Says:',ctime(),data.encode('utf8')

tcpclient.close()
s.close()

 客户端

# coding:utf-8

#  __author__ = 'Mark sinoberg'
#  __date__ = '2016/7/7'
#  __Desc__ = 简单的tcp socket客户端的实现

from socket import *

class TcpClient:
  # HOST = 'localhost'
  PORT = 9999
  HOST = '192.168.59.225'
  BUFFSIZ = 1024
  ADDR = (HOST,PORT)
  def __init__(self):
    self.client = socket(AF_INET,SOCK_STREAM)
    self.client.connect((self.HOST,self.PORT))

    while True:
      senddata = raw_input('>>>')
      if not senddata:
        print 'Please input some words!n>>>'
        continue
      if senddata == "quit":
        break
      self.client.send(senddata.encode('utf8'))
      recvdata = self.client.recv(self.BUFFSIZ)
      if not recvdata:
        break
      print recvdata.encode('utf8')

if __name__ == "__main__":
  client = TcpClient()

TCP方式演示结果:(注意先开启服务器端)

服务器端

D:SoftwarePython2python.exe E:/Code/Python/MyTestSet/sockettest/SimpleTCPServer.py
Waiting for clients cennect!
Connected By  ('192.168.59.225', 63095)
('192.168.59.225', 63095)  Says: Thu Jul 07 16:01:10 2016 Hello World
('192.168.59.225', 63095)  Says: Thu Jul 07 16:01:15 2016 haode
No Data received!
Waiting for clients cennect!

客户端

D:SoftwarePython2python.exe E:/Code/Python/MyTestSet/sockettest/SimpleTcpClient.py
>>>Hello World
Hi,you send me:[Thu Jul 07 16:01:10 2016]Hello World
>>>
Please input some words!
>>>
>>>haode
Hi,you send me:[Thu Jul 07 16:01:15 2016]haode
>>>quit

Process finished with exit code 0

总结

简单的使用TCP或者是UDP确实很容易,然而要想更好的利用这两个协议,就需要好好的设计一番了。

这里我想强调的是,注意tcp和udp创建套接字时指定的参数即可。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持帮客之家。

相对于Java方式的聊天室,Python同样可以做得到。而且可以做的更加的优雅。想必少了那么多的...

基于进程内通讯的python聊天室实现方法,python聊天室

本文实例讲述了基于进程内通讯的python聊天室实现方法。分享给大家供大家参考。具体如下:

#!/usr/bin/env python
# Added by <[email protected]>
import sys
import os
from multiprocessing import connection
ADDR = ('', 9997)
AUTH_KEY = '12345'
class Server(object):
  def __init__(self, username):
    self.auth_key = AUTH_KEY
    self.addr = ADDR
    self.username = username
    self.listener = connection.Listener(self.addr, authkey=self.auth_key)
  def listen(self):
    while True:
      conn = self.listener.accept()
      while True:
        try:
          request = conn.recv()
          response = self.response(request)
          conn.send(response)
        except EOFError:
          break
      conn.close()
  def reply(self):
    message = raw_input("%s: " % self.username)
    return message
  def output_request(self, request):
    sys.stdout.write('%s says: %sn' % request)
  def response(self, request):
    self.output_request(request)
    response = (self.username, self.reply())
    return response
class Client(object):
  def __init__(self, username):
    self.auth_key = AUTH_KEY
    self.addr = ADDR
    self.username = username
    self.display_name = self.make_display_name(username)
  def make_display_name(self, username):
    return "%s: " % username
  def connect(self):
    self.conn = connection.Client(self.addr, authkey=self.auth_key)
    while True:
      message = raw_input(self.display_name)
      self.send(message)
      response = self.conn.recv()
      self.output_response(response) 
  def send(self, message):
    self.conn.send((self.username, message))
  def output_response(self, response):
    sys.stdout.write('%s says: %sn' % response)
def main():
  mode = sys.argv[1]
  if mode == 'server':
    username = raw_input("Your name please: ")
    server = Server(username)
    server.listen()
  elif mode == 'client':
    username = raw_input("Your name please: ")
    client = Client(username)
    client.connect()
if __name__ == '__main__':
  main()

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

本文实例讲述了基于进程内通讯的python聊天室实现方法。分享给大家供大家参考。具体...

本文由美高梅游戏网站发布于智能家电,转载请注明出处:小小聊天室Python代码实现,聊天室python代码

关键词: