我正在处理银行应用程序。我想创建多线程 tcp iso8583 服务器。可同时处理存折打印请求。多个设备从不同位置连接到服务器。
我将在我的应用程序中使用以下代码。
这个线程安全吗?如果我使用此代码,我将来会遇到任何问题吗?请建议我。
class Program
{
static void Main(string[] args)
{
TcpListener serverSocket = new TcpListener(8888);
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)
{
this.clientSocket = inClientSocket;
this.clNo = clineNo;
Thread ctThread = new Thread(doChat);
ctThread.Start();
}
private void doChat()
{
int requestCount = 0;
byte[] bytesFrom = new byte[10025];
string dataFromClient = null;
Byte[] sendBytes = null;
string serverResponse = null;
string rCount = null;
requestCount = 0;
while ((true))
{
try
{
var respose = "";
requestCount = requestCount + 1;
NetworkStream networkStream = clientSocket.GetStream();
networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);
dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);
// dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"));
Console.WriteLine(" >> " + "From client-" + clNo + dataFromClient);
try
{
var isoPassbookRequestMessage = System.Text.Encoding.ASCII.GetString(bytesFrom);
WebClient wc = new WebClient();
NameValueCollection input = new NameValueCollection();
input.Add("isoPassbookRequest", Convert.ToBase64String(bytesFrom));
respose = Encoding.ASCII.GetString(wc.UploadValues("http://localhost:52835/Transaction/PassbookTransactionRequest", input));
try
{
// CommonMethods.AddtoLogFile("PassbookTransactionResponse = Clientid-" + clientID + " ProcessingCode -930000 Message -" + respose);
// atmServer.Send(clientID, Encoding.ASCII.GetBytes(respose));
}
catch (SocketException se)
{
//could not complete transaction
//Send reversal to CBS
}
}
catch (Exception e)
{
}
rCount = Convert.ToString(requestCount);
serverResponse = "Server to clinet(" + clNo + ") " + rCount;
sendBytes = Encoding.ASCII.GetBytes(respose);
networkStream.Write(sendBytes, 0, sendBytes.Length);
networkStream.Flush();
Console.WriteLine(" >> " + serverResponse);
}
catch (Exception ex)
{
Console.WriteLine(" >> " + ex.ToString());
}
}
}
}