Socket server and client written in Python

Source: Internet
Author: User

Server:

#! /Usr/bin/python

Import socket

Host = '2017. 0.0.1'

Port = 8123

S = socket. socket (socket. AF_INET, socket. SOCK_STREAM)

S. bind (host, port ))

S. listen (2)

Try:

While True:

Conn, add = s. accept ()

While True:

Data2 =''

Data1 = conn. recv (3)

If data1 = 'eof ':

Conn. send ('Hello clietn1 ')

Break

If data1 = 'foe ':

Conn. send ('Hello client2 ')

Break

Data2 + = data1

Print data2

Except t KeyboardInterrupt:

Print "you have CTRL + C, Now quit"

S. close ()

Note: The server receives only three bytes of data at a time. I keep reading data in a loop and accumulate it into data2. when reading the EOF, I quit printing data2, when reading FOE, exit and print data2. EOF and FOE are the Terminator sent when the client sends the data.) When CTRLC + C is received, close the socket.


Client 1:

#! /Usr/bin/env python

Import socket

Import OS

Ss = socket. socket (socket. AF_INET, socket. SOCK_STREAM)

Ss. connect ('2017. 0.0.1 ', 127 ))

# F = open ('A', 'wb ')

Ss. sendall ('Hello ~~dddddddddddddddddddddddddddddd ')

OS. system ('sleep 1 ')

Ss. send ('eof ')

Data = ss. recv (1024)

Print "server dafu % s" % data

Ss. close ()


Client 2:

#! /Usr/bin/env python

Import socket

Import OS

Ss = socket. socket (socket. AF_INET, socket. SOCK_STREAM)

Ss. connect ('2017. 0.0.1 ', 127 ))

# F = open ('A', 'wb ')

Ss. sendall ('wokao sile ')

OS. system ('sleep 1 ')

Ss. send ('foe ')

Data = ss. recv (1024)

Print "server dafu % s" % data

Ss. close ()


This article from the "linux open source-continuous summary..." blog, please be sure to keep this source http://fantefei.blog.51cto.com/2229719/1274582

Related Article

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.