"Delayed" 写入文件 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 客户端发送的内容。但是,问题在于写入 data.txt 文件。当我第一次发送数据时,没有任何内容会写入文件。如果我再次发送它,它将按预期工作(即使在终端中打印了正确的数据)。如果我在我的数据库中添加另一行并再次发送,旧值将再次写入文件。如果我再次发送,将添加新值。

您需要关闭文件。我觉得问题出在这里。请尝试像这样添加 'finally' 块:

       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()