chat
dot NET Remotingを使った簡単なチャットプログラム。Registやサーバ名を直せば、複数マシン間でも通信可能。通常はサーバのメソッドはlockすべき。また、ネットワーク断を考慮してサーバコールはtry-catchすべき。
private void textBox1_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode != Keys.Enter) return; svr.Add(textBox1.Text + "\r\n"); textBox1.Text = ""; } public class Server : MarshalByRefObject { private string data = ""; public string Data { get { return data; } } public void Add(string s) { data += s; } } Server svr; private void Form1_Load(object sender, EventArgs e) { const int portno = 8100; System.Diagnostics.Process[] prcs = System.Diagnostics.Process.GetProcessesByName("SimpleChat"); if (prcs.Length == 1) { System.Runtime.Remoting.Channels.ChannelServices.RegisterChannel( new System.Runtime.Remoting.Channels.Tcp.TcpChannel(portno), false); backgroundWorker1.RunWorkerAsync(); System.Threading.Thread.Sleep(100); } svr = (Server)Activator.GetObject(typeof(Server), "tcp://localhost:" + portno + "/SimpleChat"); } private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { System.Runtime.Remoting.RemotingConfiguration.RegisterWellKnownServiceType( typeof(Server), "SimpleChat", System.Runtime.Remoting.WellKnownObjectMode.Singleton); } private void timer1_Tick(object sender, EventArgs e) { timer1.Stop(); string s = svr.Data; if (textBox2.Text != s) textBox2.Text = s; timer1.Start(); }
非常勤が終了。今年でお終い。