下午好,我一直在尝试制作一个类似Skype的系统,能够进入一个团体并与仅在该组内的其他人聊天,问题是我不知道如何我可以将这个聊天室分成几个,并让它们只用一台服务器相互独立
总的来说,我试图拥有一个服务器的多个聊天室,同时能够保存一个对话聊天记录并能够将其读回来
我目前的代码只能用作1个普通聊天室 服务器端:
static void Main(string[] args)
{
Socket newSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Ip);
IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, 6000);
newSocket.Bind(endPoint);
newSocket.Listen(10);
Console.Write("Waiting...\n");
while (true)
{
Socket auxSocket = newSocket.Accept();
ThreadLab a = new ThreadLab(auxSocket);
Thread novaThread = new Thread(new ThreadStart(a.Connect));
novaThread.Start();
}
}
ThreadLab类:
private Socket socket;
static int nmrUsers = 0;
static int indice;
static Socket[] listaSockets = new Socket[10];
static ArrayList listaUtilizadores = new ArrayList();
public ThreadLab(Socket s)
{
socket = s;
listaSockets[indice++] = s;
}
public void Connect()
{
IPEndPoint aux = (IPEndPoint)socket.RemoteEndPoint;
Console.Write("Client " + aux.Address.ToString() + " connected\n");
}
客户端将有读者和作者:
private static Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Ip);
private static ThreadStart tSReader;
private static ThreadStart tSWriter;
private static Thread tReader;
private static Thread tWriter;
private static string nome;
static void Main(string[] args)
{
IPEndPoint clientEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 6000);
tSReader = new ThreadStart(reader);
tSWriter = new ThreadStart(writer);
tReader = new Thread(tSReader);
tWriter = new Thread(tSWriter);
try
{
client.Connect(clientEndPoint);
}
catch (SocketException e)
{
Console.WriteLine(e.ToString());
Console.ReadLine();
return;
}
tReader.Start();
tWriter.Start();
}
public static void writer()
{
string str;
byte[] data = new byte[1024];
nome = Console.ReadLine();
data = Encoding.ASCII.GetBytes(nome);
client.Send(data, data.Length, SocketFlags.None);
do
{
str = Console.ReadLine();
data = Encoding.ASCII.GetBytes(str);
client.Send(data, data.Length, SocketFlags.None);
} while (str != "exit");
client.Shutdown(SocketShutdown.Both);
tReader.Abort();
client.Close();
}
public static void reader()
{
byte[] data = new byte[1024];
int recv;
while (true)
{
try
{
recv = client.Receive(data);
}
catch (Exception e)
{
Console.WriteLine("Erro: " + e.Message);
Console.ReadLine();
break;
}
Console.WriteLine("\n" + Encoding.ASCII.GetString(data, 0, recv));
}
}
}
在尝试为我的问题找到解决方案时遇到了一些麻烦但是没有用,如果有人可以帮我解决这个问题,我真的很感激:\
答案 0 :(得分:0)
在服务器端,每个聊天室应该有一个帖子。在此线程中,每个连接到此聊天室中的客户端应该有一个线程。聊天室应该是线程安全的,因为客户端集合...如果您不熟悉并发线程的同步,您可以使用C#中的线程安全集合:http://msdn.microsoft.com/en-us/library/dd997305(v=vs.110).aspx "不必担心[很多]同步"。
了解MVC(https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller) 它将极大地帮助您设计服务器端。