“延迟”写入 python 中的文件


"Delayed" writing to file in python

我有非常具体的问题,我不知道如何摆脱它。我正在通过网络服务器上的 php 客户端发送一些数据。代码如下所示:

<?php
session_start();
include 'db_con.php';
include('db_functions.php');
error_reporting(E_ALL);
/* Get the port for the WWW service. */
$service_port = $_SESSION['port'];
/* Get the IP address for the target host. */
$address = $_SESSION['ip'];
/* Create a TCP/IP socket. */
try {
    $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
} catch (Exception $e) {
    echo "error" . socket_strerror(socket_last_error()) . "'n";
socket_close($socket);
}
try {
    $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
} catch (Exception $e) {
    echo "error" . socket_strerror(socket_last_error()) . "'n";
    socket_close($socket);
}
$result = socket_connect($socket, $address, $service_port);
//data from database soonTM
$in = returnResults($db);
$data = "";
foreach ($in as $r){
    $data .= $r['ring_time'] . ' ' . $r['bell_mode'] . "'r'n";
}
socket_write($socket, $data, strlen($data));
echo "Reading response:'n'n"; 
while ($out = socket_read($socket, 2048)) {
    echo $out;
}
socket_close($socket);
?>

然后将数据库中的数据发送到TCP服务器,它工作得很好,因为我得到的数据与我发送的完全相同。

无论如何,这是我的TCP服务器代码:

import socket
# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Bind the socket to the port
server_address = ('10.10.10.120', 10000)
print('starting up on %s port %s' % server_address)
sock.bind(server_address)

while True:
# Listen for incoming connections
sock.listen(1)
# Wait for a connection
print('waiting for a connection')
connection, client_address = sock.accept()
try:
    print('connection from', client_address)
    # Receive the data in small chunks and retransmit it
    while True:
        data = connection.recv(2048)
        neki = 'hello rok'
        print('received "%s"' % data)
        if data:
            try:
                dataFile = open('data.txt', 'w')
                try:
                    dataFile.write(data)
                except (Exception) as inst:
                    print(type(inst))
                    print("error at writing to file")
            except (Exception) as inst:
                print(type(inst))
                print("error opening file")
            print('sending data back to the client')
            #connection.sendall(bytes(neki, 'UTF-8'))
            connection.sendall(neki)
            break
except (Exception) as inst:
    print(type(inst))
    print("error opening connection")
finally:
    # Clean up the connection
    connection.close()

它似乎工作正常,因为在终端中它会打印我通过 TCP 客户端发送的内容。但是,问题在于写入数据.txt文件。当我第一次发送数据时,不会向文件写入任何内容。如果我再次发送它,它将按预期工作(即使终端中打印了正确的数据(。如果我向数据库添加另一行并再次发送,则旧值将再次写入文件。如果我再次发送它,将添加新值。

您需要关闭文件。我认为这是问题所在。请尝试像这样添加"最终"块:

       try:
            dataFile = open('data.txt', 'w')
            try:
                dataFile.write(data)
            except (Exception) as inst:
                print(type(inst))
                print("error at writing to file")
        except (Exception) as inst:
            print(type(inst))
            print("error opening file")
        finally:
            dataFile.close()