Python3.4 Threading Socket Learning

Source: Internet
Author: User
Tags sendmsg

#!/usr/bin/env Python3
#file name:threadtest.py
#-*-Coding:utf8-*-
#-version:1.0-

Import threading, time, socket

Class Server ():
"The server class that receives the message"
def __init__ (self, port):
Self.port = Port
Self.server = Socket.socket (socket.af_inet, socket. SOCK_DGRAM)
Self.server.bind (("", Self.port))
While True:
data, addr = Self.server.recvfrom (1024)
If addr[0] = = "127.0.0.1": Continue
Print ("\nmessage comming: {}\tfrom: {}". Format (data, addr))

Class Client ():
"Send Message to client class"
def __init__ (self, port):
Self.port = Port
Self.host = "localhost"
Self.client = Socket.socket (socket.af_inet, socket. SOCK_DGRAM)

def _sendtoserver (self, msg):
Self.client.sendto (Msg.encode ("Utf-8"), (Self.host, Self.port))

Def recivemsg ():
"' processing the function that receives the message ' '
Try
serv = Server (55553)
Except Baseexception as E:
Print (str (E.ARGS))

Def sendmsg ():
' Handling the function of sending messages '
Try
Clit = Client (55553)
While True:
msg = input ("msg->")
Clit._sendtoserver (msg)
Except Baseexception as E:
Print (str (E.ARGS))

Thread_list = []
def main ():
Global Thread_list
Try
Recive_thread = Threading. Thread (target = recivemsg, name = "Recive")
Recive_thread.start ()
Thread_list.append (Recive_thread)
Send_thread = Threading. Thread (target = sendmsg, name = "Send")
Send_thread.start ()
Thread_list.append (Send_thread)
Except Baseexception as E:
Print (str (E.ARGS))


If __name__== "__main__":
Main ()


Python3.4 Threading Socket Learning

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.