【发布时间】:2011-03-20 13:01:50
【问题描述】:
在我的 .Net 课程中,我们正在制作一个简单的聊天应用程序。我们的教授给了我们一个示例代码如下:
服务器:
TcpChannel channel = new TcpChannel(8085);
ChannelServices.RegisterChannel(channel);
RemotingConfiguration.RegisterWellKnownServiceType(typeof(RemoteObject), "myobject", WellKnownObjectMode.Singleton);
Console.ReadLine();
客户:
TcpChannel channel = new TcpChannel();
ChannelServices.RegisterChannel(channel);
RemoteObject remoteObject = (RemoteObject)Activator.GetObject(typeof(RemoteObject), "tcp://localhost:8085/myobject");
remoteObject.PrintMessage("Hello world!");
Console.ReadLine();
远程对象:
[Serializable]
public class RemoteObject : MarshalByRefObject
{
public void PrintMessage()
{
Console.Write("Hello World!");
Console.ReadLine();
}
}
使用此代码,它基本上会在每次运行客户端时在服务器控制台屏幕上打印一条“Hello World”消息。但是,我们不明白这是如何工作的,因为他没有完全解释每一行的作用。我们只知道渠道。问题在于,使用这些代码,我们将创建一个聊天的 Windows 窗体。我们能够让这个应用程序发送用户提供的消息,但我们无法弄清楚如何在 Windows 窗体中执行此操作,因为我们不了解开始的代码。
如果有人可以为我们提供一些关于如何在 Windows 窗体中执行此操作的指示和指南,请告诉我们。任何意见表示赞赏。
如果这对我们有任何帮助,下面的代码就是我们现在所能做的:
public partial class Form1 : Form
{
RemoteObject ro;
public Form1()
{
InitializeComponent();
TcpChannel serverChannel = new TcpChannel(8085);
ChannelServices.RegisterChannel(serverChannel, true);
RemotingConfiguration.RegisterWellKnownServiceType(typeof(RemoteObject), "myobject", WellKnownObjectMode.Singleton);
}
private void btnSend_Click(object sender, EventArgs e)
{
try
{
ro = (RemoteObject)Activator.GetObject(typeof(RemoteObject), "tcp://" + txtIpAddress.Text + ":8085/myobject");
ro.PrintMessage(txtMessage.Text);
txtChatArea.AppendText(System.Environment.MachineName + ": " + txtMessage.Text + "\n");
txtMessage.Clear();
}
catch (SystemException error)
{
MessageBox.Show("Error 101: " + error.Message, "Connection Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
上面的代码基本上是询问第二方(与您聊天的一方)的 IP 地址,然后提供了两个文本框 - 一个用于显示对话(多行),另一个用于接受消息。此代码可以向服务器发送消息。但是,它仍然不能接受来自其他方的任何传入消息。
【问题讨论】:
标签: c# client-server chat