Home > Backend Development > Python Tutorial > Chat room Python code implementation

Chat room Python code implementation

高洛峰
Release: 2017-02-25 11:30:11
Original
1541 people have browsed it

Compared with the Java chat room, Python can also do it. And it can be done more elegantly. You will definitely like the fact that there are so many fewer Python Sockets of various streams.

As for the content related to knowledge points, I won’t go into details here.

UDP method

Server side

# 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
Copy after login

Client

# 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()
Copy after login

Isn’t it very simple? What we need to pay attention to is that the second parameter of the socket is SOCK_DGRAM. Because this is different from SOCK_STREAM in TCP mode.

TCP method

Server side

# 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()
Copy after login

Client

# 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()
Copy after login

TCP mode demonstration result: (Note first Open the server side)

Server side

D:\Software\Python2\python.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!

Client

##D:\Software\Python2\python.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

Summary

It is really easy to simply use TCP or UDP. However, if you want to make better use of these two protocols, you need to design them well. It’s time.

What I want to emphasize here is that just pay attention to the parameters specified when tcp and udp create sockets.


The above is the entire content of this article. I hope it will be helpful to everyone's study. I also hope that everyone will support the PHP Chinese website.


For more articles related to chat room Python code implementation, please pay attention to the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template