[英]In a C# web forms app using the Socket class, how can I send two consecutive messages?
我是套接字的新手。 一位同事提供了一個用Python編寫的應用程序,該應用程序具有永遠運行的TCP套接字服務器。 該程序將交付給我們的客戶,並將與客戶將提供的客戶應用程序連接。 我已經用C#編寫了一個測試WinFormas小應用程序,該應用程序應該執行客戶的客戶端應用程序所要做的事情。 我可以將一條消息從測試程序發送到服務器,然后服務器正確響應並發送回一個確認。 我現在正嘗試發送第二條消息,但出現一個異常:“已建立的連接已被您主機中的軟件中止”。 在它可以發送另一條消息之前,我需要做些什么來重置客戶端的套接字嗎?
客戶端的套接字最初是在以下循環中設置的:
while (!connected)
{
try
{
if (m_sendSocket == null)
{
m_sendSocket = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
}
m_sendSocket.Connect(sendRemoteEP);
connected = true;
btnMoveItem.Enabled = true;
btnCloseSockets.Enabled = true;
btnOpenSockets.Enabled = false;
}
catch (SocketException socketEx)
{
Thread.Sleep(5000);
}
catch (Exception ex)
{
MessageBox.Show("Failed to connect to sockets: " + ex.Message);
break;
}
}
客戶端使用以下方法發送消息:
private void SendMessage(string message)
{
// Data buffer for incoming data.
byte[] bytes = new byte[1024];
// Connect to a remote device.
try {
// Connect the socket to the remote endpoint. Catch any errors.
try
{
//Console.WriteLine("Socket connected to {0}",
// sender.RemoteEndPoint.ToString());
// Encode the data string into a byte array.
byte[] msg = Encoding.ASCII.GetBytes(message);
// Send the data through the socket.
int bytesSent = m_sendSocket.Send(msg);
// Receive the response from the remote device.
int bytesRec = m_sendSocket.Receive(bytes);
int ackDelay = 0;
while (bytesRec == 0)
{
Thread.Sleep(500);
ackDelay += 500;
if (ackDelay > 10000)
{
using (StreamWriter writer = new StreamWriter("c:/misc/mes_simulator.log", true))
{
writer.WriteLine("No transport information acknowledgement received in ten seconds.");
}
break;
}
bytesRec = m_sendSocket.Receive(bytes);
}
MessageBox.Show("Acknowledgement message: " + Encoding.ASCII.GetString(bytes, 0, bytesRec));
if (MessageBox.Show("Send duplicate message?", "Send another?", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
// Send the data through the socket AGAIN to see if we can.
bytesSent = m_sendSocket.Send(msg);
// Receive the response from the remote device.
bytesRec = m_sendSocket.Receive(bytes);
ackDelay = 0;
while (bytesRec == 0)
{
Thread.Sleep(500);
ackDelay += 500;
if (ackDelay > 10000)
{
using (StreamWriter writer = new StreamWriter("c:/misc/mes_simulator.log", true))
{
writer.WriteLine("No transport information acknowledgement received in ten seconds.");
}
break;
}
bytesRec = m_sendSocket.Receive(bytes);
}
}
//Console.WriteLine("Echoed test = {0}",
// Encoding.ASCII.GetString(bytes,0,bytesRec));
// Release the socket.
// sender.Shutdown(SocketShutdown.Send);
// sender.Close();
}
catch (ArgumentNullException ane)
{
FormattedMessageBox.Show("ArgumentNullException : {0}", ane.ToString());
}
catch (SocketException se)
{
FormattedMessageBox.Show("SocketException : {0}", se.ToString());
}
catch (Exception e)
{
FormattedMessageBox.Show("Unexpected exception : {0}", e.ToString());
}
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
}
在收到回答說這可能是服務器方面的問題之后,我將服務器降至最低限度。 問題仍在發生。 服務器接收並確認了第一條消息,但從未收到第二條消息。 這是服務器代碼:
import json
import threading
import socketserver
import time
with open('CAPS_TWMS_config.json', 'rt') as c:
caps_config = json.load(c)
# We are listening on this port and all defined IP addresses
# listenPort = 5001
listenPort = caps_config["listen_port"]
# Were to send the information to.
clientIPAddress = '127.0.0.1' # socket.gethostbyname('client')
# clientPort = 12345
clientPort = caps_config["send_port"]
dsnName = caps_config["dsn_name"]
# Message sequence number
sequence_num = 1
exit_app = False
class ListenSocketHandler(socketserver.BaseRequestHandler):
"""
The RequestHandler class for our server.
It is instantiated once per connection to the server, and must
override the handle() method to implement communication to the
client.
"""
def __init__(self, request, client_address, this_server):
socketserver.BaseRequestHandler.__init__(self, request, client_address, this_server)
self.timeout = 10
def handle(self):
try:
data = self.request.recv(1024).decode()
print (str.format("dataString[21]: {0}; dataString[24:26]: {1}", data[21], data[24:26]))
print ('ListenSocketHandler recv()-> "%s"' % data)
print ('ListenSocketHandler recv().length-> "%d"' % len(data))
if len(data) > 0:
self.request.send("I got a message!".encode())
return
except Exception as value:
print('ListenSocketHandler - %s' % str(value))
return
class ListenServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
"""
The multi-threaded server that will spawn threads running the Socket Handler for each
connection
"""
pass
if __name__ == '__main__':
try:
# Create the Server Handler for connections to this computer listening on all IP addresses,
# change '' to 'x.x.x.x' to listen on a specific IP network. This class will listen for messages # from CAPS.
server = ListenServer(('', listenPort), ListenSocketHandler)
ip, port = server.server_address
# Start a thread with the server -- that thread will then start one
# more thread for each request
server_thread = threading.Thread(target=server.serve_forever)
# Exit the server thread when the main thread terminates
server_thread.setDaemon(True)
server_thread.start()
while not exit_app:
time.sleep(1)
print ('Out of main loop.')
server.shutdown()
server.server_close()
except Exception as value:
print("Failed to do something: %s", str(value))
不,您無需執行任何操作即可發送多個消息。
聞起來好像服務器由於某種原因斷開連接,但是您沒有顯示該代碼
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.