wuyulun
Posts: 15
Joined: Tue Feb 05, 2019 9:54 pm

Need help with TCP/IP socket programming

Wed May 01, 2019 3:45 am

I have already wrote 2 program that can use Pi to take the video and send them to the cmputer, however, I need some command to send [string type] from computer to the Pi, can anyone here help me? Thank you!

here is the code:

# the first one is used on the Pi

Code: Select all

import cv2
import numpy
import socket
import struct

HOST='192.168.11.10'
PORT=9999

server=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
server.connect((HOST,PORT))
print('now starting to send frames...')

capture=cv2.VideoCapture(0)

while True:
    success, frame = capture.read()
    result, imgencode = cv2.imencode('.jpg', frame, [cv2.IMWRITE_JPEG_QUALITY, 50])
    server.sendall(struct.pack('i', imgencode.shape[0]))
    server.sendall(imgencode)
    print('have sent one frame')
# and the second is on the computer===============

Code: Select all

import cv2
import numpy
import socket
import struct

HOST='192.168.11.10'
PORT=9999
buffSize=65535

server=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
server.bind((HOST, PORT))
print('now waiting for frames...')
while True:
    data, address = server.recvfrom(buffSize)

    if len(data) == 1 and data[0] == 1:
        server.close()
        cv2.destroyAllWindows()
        exit()

    if len(data) != 4:
        length = 0
    else:
        length = struct.unpack('i', data)[0]

    data, address = server.recvfrom(buffSize)
    if length != len(data):
        continue

    data = numpy.array(bytearray(data))
    imgdecode = cv2.imdecode(data, 1)
    print('have received one frame')
    cv2.imshow('frames', imgdecode)
    if cv2.waitKey(1) == 27:
        break
server.close()
cv2.destroyAllWindows()
Now I want to send some string type from computer to Pi, how can I do that?

User avatar
MrYsLab
Posts: 314
Joined: Mon Dec 15, 2014 7:14 pm
Location: Noo Joysey, USA

Re: Need help with TCP/IP socket programming

Wed May 01, 2019 6:54 pm

Check out this tutorial https://pymotw.com/3/socket/tcp.html. It creates a client/server that sends text strings to and from the client and server over TCP/IP.

Return to “Python”