📄 15.9.txt
字号:
Listing 15.9 The UDP Chat Client Application
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace _5_UDPFormClient
{
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.TextBox tbTranscript;
private System.Windows.Forms.TextBox tbMessage;
private System.Windows.Forms.Button btnSend;
private Thread chatThread;
private System.ComponentModel.Container components = null;
private string name;
UdpClient client;
private System.Windows.Forms.TextBox tbName;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Button btnSetName;
IPEndPoint serverIP;
public Form1()
{
InitializeComponent();
serverIP = new IPEndPoint( IPAddress.Parse( “127.0.0.1” ), 2003 );
client = new UdpClient( new IPEndPoint( IPAddress.Any, 0 ));
name = tbName.Text;
// create a thread to start receiving broadcast messages
chatThread = new Thread( new ThreadStart( ReceiveBroadcast ));
chatThread.Start();
SendCommand( “300 “ + name );
}
public void ReceiveBroadcast()
{
IPEndPoint receiveIP = new IPEndPoint(IPAddress.Any, 0);
while( true )
{
byte[] data = client.Receive( ref receiveIP );
tbTranscript.Text += Encoding.ASCII.GetString( data,
0, data.Length ) + “\r\n”;
}
}
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
private void InitializeComponent()
{
this.tbTranscript = new System.Windows.Forms.TextBox();
this.tbMessage = new System.Windows.Forms.TextBox();
this.btnSend = new System.Windows.Forms.Button();
this.tbName = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.btnSetName = new System.Windows.Forms.Button();
this.SuspendLayout();
// Windows Form initialization code removed
this.ResumeLayout(false);
}
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
private void SendCommand( string command )
{
byte[] bytes = Encoding.ASCII.GetBytes(command);
int ret = client.Send(bytes, bytes.Length, serverIP );
}
private void btnSend_Click(object sender, System.EventArgs e)
{
SendCommand( “400 “ + tbMessage.Text );
}
private void btnSetName_Click(object sender, System.EventArgs e)
{
SendCommand( “301 “ + name );
SendCommand( “300 “ + tbName.Text );
name = tbName.Text;
}
private void Form1_Closed(object sender, System.EventArgs e)
{
SendCommand( “301 “ + name );
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -