本文介绍了如何接受多个客户端连接到服务器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有服务器程序,但它只接受一个客户端连接,并且在连接后它发送& quot; q& quot;,
现在我想接受更多客户端连接,并且当他们接受时给服务器输入,服务器应该发送相同的& quot; q& quot;连接后给每个客户。
I have Server program but it accepts only one client connection and after connection it sends "q",
now i want to accept more client connections and at a time when they give input to server , the server should send the same "q" to every client after connection.
class Program
{
// public static SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["TB"].ToString());
public static void Main()
{
try
{
Program pq = new Program();
string ipadd = getip();
// IPAddress ipAd = IPAddress.Parse("192.168.0.10"); //use local m/c IP address, and use the same in the client
IPAddress ip = IPAddress.Parse(ipadd);
/* Initializes the Listener */
TcpListener myList = new TcpListener(ip, 3030);
/* Start Listeneting at the specified port */
myList.Start();
Console.WriteLine("The server is running at port 3030...");
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);
for (int p = 0; p >= 0; p++)
{
byte[] b = new byte[100];
int k = s.Receive(b);
Console.WriteLine("Recieved...");
for (int i = 0; i < k; i++)
{
Console.Write(Convert.ToChar(b[i]));
}
//for (int i = 0; i <= 100; i++)
//{
ASCIIEncoding asen = new ASCIIEncoding();
s.Send(asen.GetBytes("q"));
Console.Write("q sent");
// Console.Write("I sent Q");
//}
Array.Clear(b, 0, b.Length);
}
Console.WriteLine("\nSent Acknowledgement");
/* clean up */
s.Close();
myList.Stop();
}
catch (Exception e)
{
Console.WriteLine("Error..... " + e.StackTrace);
}
}
static string getip()
{
IPHostEntry host;
string localIP = "?";
host = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
localIP = ip.ToString();
// Console.Write("My ip is " + localIP);
}
}
return localIP;
}
}
}
推荐答案
这篇关于如何接受多个客户端连接到服务器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!