我正在尝试构建一个服务器客户端应用程序(wpf)。
我想要完成的结构是:
我面临的一个问题是如何分离服务器角色。
第二个问题是如何让服务器知道它与之通信的客户端类型,发送者或接收者。
这是我的代码:
服务器:
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows;
namespace NetMessageServerWpf
{
public partial class MainWindow : Window
{
TcpClient client;
public MainWindow()
{
InitializeComponent();
this.tcpListener = new TcpListener(IPAddress.Any, 3000);
this.listenThread = new Thread(new ThreadStart(ListenForClients));
this.listenThread.Start();
}
private void btnSend_Click(object sender, RoutedEventArgs e)
{
if(client == null || !client.Connected)
client = this.tcpListener.AcceptTcpClient();
msg = txtMessage.Text;
SendTCP(client);
}
public TcpListener tcpListener;
public Thread listenThread;
private string msg;
private void ListenForClients()
{
this.tcpListener.Start();
}
public void SendTCP(TcpClient tcpClient)
{
NetworkStream clientStream = tcpClient.GetStream();
ASCIIEncoding encoder = new ASCIIEncoding();
byte[] buffer = encoder.GetBytes(this.msg);
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
}
}
}
客户端:
namespace NetClientSideWpf
{
class Client : Base
{
private string messageString;
public string MessageString
{
get { return messageString; }
set
{
messageString = value;
OnPropertyChanged("MessageString");
}
}
public Client()
{
ConnectToServer();
}
public void ConnectToServer()
{
TcpClient client = new TcpClient();
IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 3000);
client.Connect(serverEndPoint);
NetworkStream clientStream = client.GetStream();
Thread ServerThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
ServerThread.Start(client);
}
private void HandleClientComm(object client)
{
TcpClient tcpClient = (TcpClient)client;
NetworkStream clientStream = tcpClient.GetStream();
byte[] message = new byte[4096];
int bytesRead;
while (true)
{
bytesRead = 0;
try
{
bytesRead = clientStream.Read(message, 0, 4096);
}
catch
{
break;
}
if (bytesRead == 0)
{
break;
}
ASCIIEncoding encoder = new ASCIIEncoding();
MessageString = encoder.GetString(message, 0, bytesRead);
}
}
}
}
提前致谢! :)
答案 0 :(得分:0)
首先,我会将您的客户端包装在可以调用方法的Client
对象中。
然后,当客户端连接时,它应该发送一条消息,详细说明其模式:
“IAM:发件人”
OR
“IAM:Reciever”
如果您愿意,可以让第二部分解析为enum
。然后,您将根据模式对Client
个对象进行排序:
List<Client> clients;
client.Mode = Enum.Parse(typeof(ClientMode), message.Split(':')[1]);
clients.Add(client);
当“发送者”发送“广播”消息时,您会将其写入Client
列表中的每个recievers
对象。这将在客户端读取线程
if (sender.Type == ClientMode.Sender)
{
foreach (Client client in clients.Where(c => c.Type == ClientMode.Sender)
client.Send(message)
}
显然,这些是非常广泛的,并且完全实施对于SO来说太大了。希望这能让你走上正轨,如果我能澄清任何事情,请告诉我!