我正在使用套接字进行TCP-IP连接,我想从客户端建立简单的系统发送 - 接收。
Socket sck;
sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint localEndpt = new IPEndPoint(IPAddress.Parse("123.123.123.1"), 12345);
try
{
sck.Connect(localEndpt);
}
catch
{
Console.Write("Unable to Connect");
}
while (true)
{
Console.WriteLine("Enter Text");
string sendtext = Console.ReadLine();
byte[] Data = Encoding.ASCII.GetBytes(sendtext);
sck.Send(Data);
Console.WriteLine("Data Sent!");
byte[] bytesReceived = new byte[sck.ReceiveBufferSize];
int bytes = 0;
String strReceived = "";
int dataAvailable = 0;
while (dataAvailable == 0 || dataAvailable != sck.Available)
{
dataAvailable = sck.Available;
Thread.Sleep(100); // if no new data after 100ms assume transmission finished
}
if (sck.Available > 0)
{
bytes = sck.Receive(bytesReceived, bytesReceived.Length, 0);
strReceived+=Encoding.ASCII.GetString(bytesReceived, 0, bytes);
}
Console.WriteLine("Received from server: " + strReceived);
}
Console.Read();
问题在于第一个请求是通过,但第二个请求没有,因为套接字不再可用(套接字"可用"属性值为0)。我究竟做错了什么?建立多个发送 - 接收请求(按顺序)最简单的方法是什么?
答案 0 :(得分:1)
Thread.Sleep
NOT 指示套接字是否可用,但是传入的数据可供阅读:
Liskov Substitution Principle
您的程序退出是因为它在发送消息后立即检查回复(传入数据)。在检查数据之前使用Socket.Send
。
可能还没有发送消息,因为{{1}}只是将它放在网络接口卡的输出缓冲区中。当套接字最终发送消息时,它将升级连接状态。如果没有回复(在TCP连接上),它将告诉您在查询状态时它已断开连接。在UDP上它不会告诉你什么,因为UDP是无连接的。
答案 1 :(得分:1)
此代码适用于我
let a = 'object string';let jsObj = JSON.parse(a);console.log(jsObj);
只需运行此代码即可开始使用
private List<Socket> _clients = new List<Socket>();
private Thread _dataReceiveThread;
private bool _isConnected;
private void DataReceive()
{
while (_isConnected)
{
List<Socket> clients = new List<Socket>(_clients);
foreach (Socket client in clients)
{
try
{
if (!client.Connected) continue;
string txt = "";
while (client.Available > 0)
{
byte[] bytes = new byte[client.ReceiveBufferSize];
int byteRec = client.Receive(bytes);
if (byteRec > 0)
txt += Encoding.UTF8.GetString(bytes, 0, byteRec);
}
if (!string.IsNullOrEmpty(txt))
/* TODO: access the text received with "txt" */
}
catch (Exception e)
{
Exception_Handler(e);
}
}
}
}
更新_isConnected = true;
_dataReceiveThread = new Thread(DataReceive);
_dataReceiveThread.Start();
中的列表框:
此代码可以放在评论部分。
Cross thread