【发布时间】:2015-12-23 07:18:02
【问题描述】:
我有两个应用程序,一个是 tcpclient,另一个是 tcp 服务器。我将字符串作为数据从 tcpclient 发送到 tcp 服务器。在单个客户端的情况下一切正常,但是当我尝试从不同的机器运行另一个客户端时,我收到异常“远程主机强制关闭连接”请帮助我如何将多个客户端连接到单个 tcp 服务器这是我的代码。
/*TCP SERVER*/
static void Main(string[] args)
{
//192.168.0.105
IPAddress ipAd = IPAddress.Parse("192.168.0.100");
// use local m/c IP address, and
// use the same in the client
FileStream f = File.Open("D:/GPSResearchandDevelopment/GPSService/GPSService/abc.txt", FileMode.OpenOrCreate);
IAsyncResult a = null;
connection:
Console.WriteLine("reCHED TO THE CONNECTION");
TcpListener myList = new TcpListener(ipAd, 8001);
myList.Start();
Console.WriteLine("The server is running at port 8001...");
Console.WriteLine("The local End point is :" +
myList.LocalEndpoint);
Console.WriteLine("Waiting for a connection.....");
Socket s = myList.AcceptSocket();
Console.WriteLine("Connection accepted from " + s.RemoteEndPoint);
byte[] b = new byte[100];
int k = s.Receive(b);
Console.WriteLine("Recieved...");
a = f.BeginWrite(b, 0, b.Length, null, null);
f.EndWrite(a);
String[] str = Encoding.UTF8.GetString(b).Split('|');
for (int i = 0; i < str.Length; i++)
Console.WriteLine(str[i]);
ASCIIEncoding asen = new ASCIIEncoding();
s.Send(asen.GetBytes("The string was recieved by the server."));
Console.WriteLine("\nSent Acknowledgement");
//s.Close();
myList.Stop();
goto connection;
}
/*TCP CLIENT*/
static void Main(string[] args)
{
CONNECTAGAIN:
TcpClient tcpclnt = new TcpClient();
Console.WriteLine("Connecting.....");
tcpclnt.Connect("192.168.0.100", 8001);
// use the ipaddress as in th1e server program
Console.WriteLine("Connected");
Console.Write("Enter the string to be transmitted : ");
String str = Console.ReadLine();
//String str = "supriya|laxman|medankar";
Stream stm = tcpclnt.GetStream();
ASCIIEncoding asen = new ASCIIEncoding();
byte[] ba = asen.GetBytes(str);
Console.WriteLine("Transmitting.....");
stm.Write(ba, 0, ba.Length);
byte[] bb = new byte[100];
int k = stm.Read(bb, 0, 100);
for (int i = 0; i < k; i++)
{
Console.Write(Convert.ToChar(bb[i]));
}
tcpclnt.Close();
// Console.ReadLine();
goto CONNECTAGAIN;
}
【问题讨论】:
-
您想同时进行多个连接吗?在这种情况下,您需要一些并行运行的线程来接受传入的连接尝试。
-
简而言之,您需要为每个客户端创建和维护一个套接字和线程。您编写的代码一次只允许一个连接。接收调用应该在单独的线程上进行,因为它是一个阻塞调用。
-
是的,我想要多个连接@同时