[英]Is there a way to send array on javascript to controller other than get or post method??
[英]Is there a way to get tcp server to send responses other than echoing incoming messages?
我显然是 TCP 服务器的新手。 下面的代码工作得很好——它“只”回应了它收到的消息。 但我的问题是“简单的”:我怎样才能向我的客户发送响应——而不是像下面那样简单地回应请求? 例如,如果我想发回数据(特别是对我来说,XML 中的“OFML”数据,类似于刑事司法最终用户的表格)。
但我会满足于“Hello world!”!
我所做的所有尝试都导致我的客户端崩溃(我无法共享其专有代码) - 以及一些自定义错误消息,例如“未找到数据包”。
任何建议将不胜感激 - 或参考一些关于如何完成此任务的明确文档。
哦 - 我可能会补充一点,我只是想创建一个简单的“模拟”服务器,用于客户端的本地调试 - 即这永远不会用于“生产”。 谢谢!
using System.Drawing;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Net.NetworkInformation;
using System.Threading;
namespace FoxTalkMOCK
{
class Program
{
public static void Main()
{
TcpListener server = null;
try
{
Int32 port = 8080;
IPAddress localAddr = IPAddress.Parse("10.116.45.49");
server = new TcpListener(localAddr, port);
server.Start();
// Buffer for reading data
Byte[] bytes = new Byte[18];
String data = null;
// Enter the listening loop.
while (true)
{
Console.Write("Waiting for a connection... ");
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("Connected!");
data = null;
// Get a stream object for reading and writing
NetworkStream stream = client.GetStream();
int i;
// Loop to receive all the data sent by the client.
try
{
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
// Translate data bytes to a ASCII string.
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
Console.WriteLine("Received: {0}", data);
// Process the data sent by the client.
data = data.ToUpper();
string bitString = BitConverter.ToString(bytes);
bitString = bitString.Replace("-", ", 0x");
bitString = "0x" + bitString;
Console.WriteLine(bitString);
// *******************Send response*********************
stream.Write(bytes, 0, bytes.Length);
Console.WriteLine("Sent: {0}", System.Text.Encoding.ASCII.GetString(bytes, 0, bytes.Length));
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
// Shutdown and end connection
client.Close();
}
}
catch (SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
}
finally
{
// Stop listening for new clients.
server.Stop();
}
Console.WriteLine("\nHit enter to continue...");
Console.Read();
}
}
}```
该示例连接并接收数据,然后将该数据发回并断开连接。
如果要保留插座,请保留它而不会损坏。
每当你保存它并再次写入它时,你可以通过异常处理来管理套接字是否被维护。
简单返回“hello world”的答案如下:
var strBuffer = "Hello World!";
byte[] array = new byte[strBuffer.Length];
array = System.Text.Encoding.ASCII.GetBytes(strBuffer);
stream.Write(array, 0, array.Length)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.