[CENTOS] Communication processing by Python

Communication processing by Python This article is the 21st day article of Keio University SFC Murai & Tokuda Lab Advent Calendar 2015.

1.First of all

Until the summer, I started to touch the PC from the fall semester because I was disgusted with myself talking about research significance and services without implementing it at the level of "what is UNIX command". Then I started to touch Swift and Python and now I'm writing Python.

After all, I'm new to programming. This time I will write about socket communication in Python.

Contents of this time

Set up a TCP server using only Python and perform socket communication with a TCP client.

2. Environment

3. Source code text and procedure (see comment out)

Since the handling of data types is different between python2 series and 3 series, the correction of that is added. (Also print () and input ())

Basically, we will follow the steps using the socket library. First, let's create a TCP client.

client.py (Python2 series)


# -*- coding:utf-8 -*-
import socket

host = "xxx.xxx.xxx.xxx" #Enter the host name of your server
port = xxxx #I will specify an appropriate PORT

client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #Create an object

client.connect((host, port)) #Now connect to the server

client.send("from nadechin") #Send the appropriate data (as the recipient knows)

response = client.recv(4096) #Receive should be an appropriate power of 2 (not too large)

print response

client.py (Python3 series)


# -*- coding:utf-8 -*-
import socket

host = "xxx.xxx.xxx.xxx" #Enter the host name of your server
port = xxxx #I will specify an appropriate PORT

client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #Create an object

client.connect((host, port)) #Now connect to the server

massage = "from nadechin"

client.send(massage.encode('utf-8')) #Send the appropriate data (as the recipient knows)

response = client.recv(4096) #Receive should be an appropriate power of 2 (not too large)

print(response)

It is the basis of servers and clients that use Python, and it can be widely applied by expanding it. UDP clients can be created in much the same way. (There is no need to call connect () for UDP communication)

Next, let's create a TCP server. Naturally, this is also written in the same way as the TCP client form above.

server.py (Python2 series)


# -*- coding:utf-8 -*-
import socket

host = "xxx.xxx.xxx.xxx" #Enter the host name of your server
port = xxxx #I will specify the same PORT set on the client

serversock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
serversock.bind((host,port)) #Bind by specifying IP and PORT
serversock.listen(10) #Listen for a connection (specify the maximum number of queues)

print 'Waiting for connections...'
clientsock, client_address = serversock.accept() #Store data when connected

while True:
    rcvmsg = clientsock.recv(1024)
    print 'Received -> %s' % (rcvmsg)
    if rcvmsg == '':
      break
    print 'Type message...'
    s_msg = raw_input()
    if s_msg == '':
      break
    print 'Wait...'

    clientsock.sendall(s_msg) #Returns a message
clientsock.close()

server.py (Python3 series)


# -*- coding:utf-8 -*-
import socket

host = "xxx.xxx.xxx.xxx" #Enter the host name of your server
port = xxxx #I will specify the same PORT set on the client

serversock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
serversock.bind((host,port)) #Bind by specifying IP and PORT
serversock.listen(10) #Listen for a connection (specify the maximum number of queues)

print('Waiting for connections...')
clientsock, client_address = serversock.accept() #Store data when connected

while True:
    rcvmsg = clientsock.recv(1024)
    print('Received -> %s' % (rcvmsg))
    if rcvmsg == '':
      break
    print('Type message...')
    s_msg = input().replace('b', '').encode('utf-8')
    if s_msg == '':
      break
    print('Wait...')

    clientsock.sendall(s_msg) #Returns a message
clientsock.close()

4. Try it out

1

Server side (CentOS)


$ python server.py
Waiting for connections...

2

Client side (MacBook)


$ python client.py 

3

Server side (CentOS)


$ python server.py
Waiting for connections...
Received -> from nadechin
Type message...
Hello World!

4

Client side (MacBook)


$ python client.py 
Hello World!

5

Server side (CentOS)


$ python server.py
Waiting for connections...
Received -> from nadechin
Type message...
Hello World!
Wait...
Received -> 

You can have a little chat like this. If you change the method, you can exchange infinitely, or if you ignore the acceptance of the message, you can keep the right to speak even after speaking.

5. Conclusion

It was an announcement that feels like a small fish, but thank you for giving me the opportunity to write in such a place. In the future, I would like to learn C language little by little and deepen my understanding of networks.

6. Addendum

I did socket programming in C language and confirmed that I could actually do it. Recently, I've been eating a lot of things, but I'm starting to get interested in Honeypot and system programming, so I'll write again when each result comes out.

References

Justin Seitz (2014) "Cyber Security Programming" Kazushi Aoki, Yu Arai, Saya Ichinose, Makoto Iwamura, Yuhei Kawakotani, Yuji Hoshizawa

Recommended Posts

Communication processing by Python
Socket communication and multi-thread processing by Python
Image processing by python (Pillow)
100 Language Processing Knock Chapter 1 by Python
python image processing
Python file processing
Image processing by Python 100 knock # 1 channel replacement
Grayscale by matrix-Reinventor of Python image processing-
100 image processing by Python Knock # 6 Color reduction processing
Socket communication by C language and Python
Primality test by Python
Python distributed processing Spartan
Serial communication with python
File processing in Python
Python: Natural language processing
Visualization memo by Python
Multithreaded processing in python
First Python image processing
Text processing in Python
Queue processing in Python
WiringPi-SPI communication using Python
Image processing with Python
HTTP communication with Python
Beamformer response by python
Image processing by Python 100 knock # 11 smoothing filter (average filter)
Python string processing illustration
Various processing of Python
[Language processing 100 knocks 2020] Summary of answer examples by Python
Image processing by matrix Basics & Table of Contents-Reinventor of Python image processing-
Send data from Python to Processing via socket communication
Learn Python asynchronous processing / coroutines by comparing with Node.js
Image processing with Python (Part 2)
100 Language Processing with Python Knock 2015
UTF8 text processing in python
Speech recognition by Python MFCC
"Apple processing" with OpenCV3 + Python3
EXE Web API by Python
Newcomer training program by Python
Parameter setting by python configparser
Pin python managed by conda
Acoustic signal processing with Python (2)
Acoustic signal processing with Python
Asynchronous processing (threading) in python
100 Language Processing Knock Chapter 1 (Python)
100 Language Processing Knock Chapter 2 (Python)
Introduction to serial communication [Python]
Image processing with Python (Part 1)
Keyword extraction by MeCab (python)
Separate numbers by 3 digits (python)
View Python communication with Fiddler
Markov switching model by Python
Image processing with Python (Part 3)
Post processing of python (NG)
Python started by C programmers
Image Processing Collection in Python
Using Python mode in Processing
Platform (OS) determination by Python
Sort by date in python
[Python] Iterative processing (for, while)
[Python] Image processing with scikit-image
Improve your productivity by processing huge Excel files with Python