多线程TCP服务器异常 [英] Multi Thread TCP Server Exception
问题描述
我创建了一个TCP服务器,它监听客户端执行某些命令并返回数据。我不熟悉socket和amp;多线程编程,我想我已用多线程编写,但运行多客户端时会发生异常。我现在正在尝试的是,我试图从我的本地机器运行服务器和多客户端,这是问题吗?
这是代码。
Hi,
I have created a TCP server which listens to client(s) executes some commands and returns the data. I am new to both socket & multi thread programming and I think i have written in multi thread , but an exception is happening when multi client are run. What i am trying now is that I am trying to run both server and multi clients from my local machine, will that be the issue?
Here is the code .
public class TCPServer
{
/// <summary>
/// Local Variables Declaration.
/// </summary>
private TcpListener m_server = null;
private bool m_stopServer = false;
private Thread m_serverThread = null;
private ArrayList m_socketListenersList = null;
/// <summary>
/// Constructors.
/// </summary>
public TCPServer()
{
//Change this to get the machines IP and port as per appsettings
IPAddress ipAddress = IPAddress.Parse(ConfigurationManager.AppSettings["IPAddress"]);
int portNumber = Convert.ToInt32(ConfigurationManager.AppSettings["PortNumber"]);
if (ipAddress != null && portNumber > 0)
{
Init(new IPEndPoint(IPAddress.Any, portNumber));
}
else
{
Console.WriteLine("IP address / Port number not found!!!");
}
}
/// <summary>
/// Init method that create a server (TCP Listener) Object based on the
/// IP Address and Port information that is passed in.
/// </summary>
/// <param name="ipNport"></param>
private void Init(IPEndPoint ipNport)
{
try
{
m_server = new TcpListener(ipNport);
string filePath = ConfigurationManager.AppSettings["ExecutablePath"];
if (!Directory.Exists(filePath))
{
throw new Exception("Path not found");
}
}
catch (Exception e)
{
m_server = null;
}
}
/// <summary>
/// Method that starts TCP/IP Server.
/// </summary>
public void StartServer()
{
if (m_server != null)
{
// Create a ArrayList for storing SocketListeners before
// starting the server.
m_socketListenersList = new ArrayList();
// Start the Server and start the thread to listen client
// requests.
m_server.Start();
Console.WriteLine("The server is running at port " + ConfigurationManager.AppSettings["PortNumber"] + "...");
Console.WriteLine("The local End point is :" +
m_server.LocalEndpoint);
Console.WriteLine("Waiting for a connection.....");
m_serverThread = new Thread(new ThreadStart(ServerThreadStart));
m_serverThread.Start();
}
}
/// <summary>
/// Method that stops the TCP/IP Server.
/// </summary>
public void StopServer()
{
if (m_server != null)
{
// It is important to Stop the server first before doing
// any cleanup. If not so, clients might being added as
// server is running, but supporting data structures
// (such as m_socketListenersList) are cleared. This might
// cause exceptions.
// Stop the TCP/IP Server.
m_stopServer = true;
m_server.Stop();
// Wait for one second for the the thread to stop.
m_serverThread.Join(1000);
// If still alive; Get rid of the thread.
if (m_serverThread.IsAlive)
{
m_serverThread.Abort();
}
m_serverThread = null;
// Free Server Object.
m_server = null;
// Stop All clients.
StopAllSocketListers();
}
}
/// <summary>
/// Method that stops all clients and clears the list.
/// </summary>
private void StopAllSocketListers()
{
foreach (TCPSocketListener socketListener
in m_socketListenersList)
{
socketListener.StopSocketListener();
}
// Remove all elements from the list.
m_socketListenersList.Clear();
m_socketListenersList = null;
}
/// <summary>
/// TCP/IP Server Thread that is listening for clients.
/// </summary>
private void ServerThreadStart()
{
// Client Socket variable;
Socket clientSocket = null;
TCPSocketListener socketListener = null;
while (!m_stopServer)
{
try
{
// Wait for any client requests and if there is any
// request from any client accept it (Wait indefinitely).
clientSocket = m_server.AcceptSocket();
Console.WriteLine("Connection accepted from " + clientSocket.RemoteEndPoint);
// Create a SocketListener object for the client.
socketListener = new TCPSocketListener(clientSocket);
// Add the socket listener to an array list in a thread.safe fashion.
lock (m_socketListenersList)
{
m_socketListenersList.Add(socketListener);
}
// Start a communicating with the client in a different
// thread.
socketListener.StartSocketListener();
}
catch (SocketException)
{
m_stopServer = true;
}
catch (Exception ex)
{
}
}
}
}
我正在使用的代码,我得到了它来自Code Project本身的帖子
当我尝试运行第二个客户端实例时,我在accpet套接字区域出错。
请帮帮我
谢谢&问候
Arjun Menon
The code I am using , I got it from a post in Code Project itself
When i try to run the second client instance I get error at the accpet socket area.
Please help me out
Thanks & Regards
Arjun Menon
推荐答案
而是创建自己的线程,你可以使用异步编程模型。
MSDN在客户端和服务器端都有一些很好的例子。
异步服务器套接字示例 [ ^ ]
使用异步服务器套接字 [ ^ ]
我认为你会发现这种编程方式更强大,更容易出问题。
Instead creating your own threads you can make use of the asynchronous programming model.
MSDN has some pretty good examples for both client and server side.
Asynchronous Server Socket Example[^]
Using an Asynchronous Server Socket[^]
I think you will find this way of programming more robust and easier to trouble shoot.
这篇关于多线程TCP服务器异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!