Home Backend Development Python Tutorial Chat room Python code implementation

Chat room Python code implementation

Feb 25, 2017 am 11:30 AM

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the permissions problem encountered when viewing Python version in Linux terminal? How to solve the permissions problem encountered when viewing Python version in Linux terminal? Apr 01, 2025 pm 05:09 PM

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

How to teach computer novice programming basics in project and problem-driven methods within 10 hours? How to teach computer novice programming basics in project and problem-driven methods within 10 hours? Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? Apr 01, 2025 pm 11:15 PM

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

How does Uvicorn continuously listen for HTTP requests without serving_forever()? How does Uvicorn continuously listen for HTTP requests without serving_forever()? Apr 01, 2025 pm 10:51 PM

How does Uvicorn continuously listen for HTTP requests? Uvicorn is a lightweight web server based on ASGI. One of its core functions is to listen for HTTP requests and proceed...

How to get news data bypassing Investing.com's anti-crawler mechanism? How to get news data bypassing Investing.com's anti-crawler mechanism? Apr 02, 2025 am 07:03 AM

Understanding the anti-crawling strategy of Investing.com Many people often try to crawl news data from Investing.com (https://cn.investing.com/news/latest-news)...

How to dynamically create an object through a string and call its methods in Python? How to dynamically create an object through a string and call its methods in Python? Apr 01, 2025 pm 11:18 PM

In Python, how to dynamically create an object through a string and call its methods? This is a common programming requirement, especially if it needs to be configured or run...

See all articles