c#线程使用套接字继续运行
本文关键字:继续 运行 套接字 线程 | 更新日期: 2023-09-27 18:20:50
我有一个程序,其中我需要侦听多个客户端,这些客户端在特定间隔后从网络发送数据,然后将数据插入数据库。我已经编写了一个多线程程序,但在侦听时,一个线程随机运行到无限循环中,而实际上并没有从客户端读取数据。这是我的代码:
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
TcpListener serverSocket = new TcpListener(IPAddress.Parse("my.ip.add.ress"),myport);
TcpClient clientSocket = default(TcpClient);
int counter = 0;
serverSocket.Start();
Console.WriteLine(" >> " + "Server Started");
counter = 0;
while (true)
{
counter += 1;
clientSocket = serverSocket.AcceptTcpClient();
Console.WriteLine(" >> " + "Client No:" + Convert.ToString(counter) + " started!");
handleClinet client = new handleClinet();
client.startClient(clientSocket, Convert.ToString(counter));
}
clientSocket.Close();
serverSocket.Stop();
Console.WriteLine(" >> " + "exit");
Console.ReadLine();
}
}
//Class to handle each client request separatly
public class handleClinet
{
TcpClient clientSocket;
string clNo;
public void startClient(TcpClient inClientSocket, string clineNo)
{
Console.WriteLine("In start client");
this.clientSocket = inClientSocket;
this.clNo = clineNo;
Thread ctThread = new Thread(doChat);
ctThread.Start();
}
private void doChat()
{
Console.WriteLine("In doChat");
byte[] bytesFrom = new byte[251];
string data = null;
string connectionString = null;
SqlConnection cnn ;
connectionString = "some connection string";
while ((true))
{
try
{
NetworkStream networkStream = clientSocket.GetStream();
networkStream.Read(bytesFrom, 0, bytesFrom.Length);
data = System.Text.Encoding.ASCII.GetString(bytesFrom);
//networkStream.Flush();
//Console.WriteLine(" >> " + "From client-" + clNo + data.Trim());
//get message type from device
String gMsgType = data.Slice(13,17);
Console.WriteLine("{0}",gMsgType);
//if the msg BP05 use it else continue
if(String.Compare("BP05",gMsgType) !=0 )
throw new Exception();
//we got bp05 message parse the inputs
String gId = data.Slice(18,32);
String gDate = data.Slice(32,38);
String gStatus = data.Slice(38,39);
String gLat = data.Slice(39,48);
String gLon = data.Slice(49,59);
String gSpeed = data.Slice(60,65);
String gTime = data.Slice(65,71);
String gInputs = data.Slice(77,85);
String gMileData = data.Slice(86,92);
if(String.Compare("A", gStatus)==0)
{
//sanitize inputs before insertion
//some operations
Console.WriteLine("{0}",data);
//connect to database
cnn = new SqlConnection(connectionString);
cnn.Open();
SqlCommand com = new SqlCommand();
com.Connection = cnn;
com.CommandText = "some insert query"
com.ExecuteNonQuery();
cnn.Close();
}
}
catch (Exception ex)
{
Console.WriteLine(" >> " + ex.ToString());
break;
}
}
}
}
}
首先,删除while(true)循环并使用某种条件。如果需要,可以更改"isRunning"布尔值以结束程序。其次,
networkStream.Read(bytesFrom, 0, bytesFrom.Length);
如果我没有记错的话,应该返回从套接字读取的字节数。如果客户端已断开连接,则可以从套接字读取0个字节。如果从套接字读取0个字节,我会从那里开始并中断。
也许networkStream。Read是一个阻塞函数,为什么不尝试为Read函数设置超时?