TCPIPclientTest.py

You can view and download this file on Github: TCPIPclientTest.py

 1#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 2# This is an EXUDYN example
 3#
 4# Details:  Example for connecting two Python codes via TCP/IP
 5#           See file TCPIPserverTest.py for running on the other Python instance
 6#
 7# Author:   Johannes Gerstmayr
 8# Date:     2021-11-06
 9#
10# Copyright:This file is part of Exudyn. Exudyn is free software. You can redistribute it and/or modify it under the terms of the Exudyn license. See 'LICENSE.txt' for more details.
11#
12#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
13
14
15import socket
16import sys
17import time
18import struct
19packer = struct.Struct('I d d d d')
20ackPacker = struct.Struct('I')
21
22HOST='127.0.0.1'
23PORT = 65124
24# Create a TCP/IP socket
25sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
26
27# Connect the socket to the port where the server is listening
28server_address = (HOST, PORT)
29print('connecting to %s port %s' % server_address)
30sock.connect(server_address)
31# After the connection is established, data can be sent through the socket with sendall() and received with recv(), just as in the server.
32
33
34t = 0
35try:
36
37    # Send data
38    # message = 'This is the message.  It will be repeated.'
39    # print('sending "%s"' % message)
40    # byteMessage=message.encode(encoding='utf-8')
41    # sock.sendall(byteMessage)
42
43    while t < 10:
44        x=1.13
45        y=4
46        z=-3.1415
47        values = (4, t, x, y, z)
48        byteMessage = packer.pack(*values)
49        print("send", values)
50        sock.sendall(byteMessage)
51        chksum = sum(byteMessage)
52        ackData = ackPacker.pack(chksum)
53
54        ackReceived = False
55        timeout = 0
56        while not ackReceived:
57            data = sock.recv(len(ackData)) #recv waits until it receives the package!
58            # if (len(data)):
59            #     print(data, len(data), ackPacker.unpack(data)[0] ,'==', chksum)
60            if len(data) == len(ackData) and ackPacker.unpack(data)[0] == chksum:
61                print('  ok (', ackPacker.unpack(data)[0], ')')
62                ackReceived = True
63            else:
64                print('error in checksum; check your connection')
65                ackReceived = True
66
67        time.sleep(0.5)
68        t+=0.5
69
70        # Look for the response
71        # amount_received = 0
72        # amount_expected = len(byteMessage)
73
74        # while amount_received < amount_expected:
75        #     data = sock.recv(16)
76        #     amount_received += len(data)
77        #     print('received "%s"' % data)
78
79finally:
80    print('closing socket')
81    sock.close()