📄 socketusercontrol.cs
字号:
/************************************************************
SocketUserControl.cs
CopyRight 2000-2001
This is a sample program made by Saurabh Nandu.
E-mail: saurabh@mastercsharp.com
Website: http://www.mastercsharp.com
Socket Chat Internet Explorer COntrol
Compilation:
csc /t:library SocketUserControl.cs
29/September/2001
************************************************************/
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
using System.Text;
using System.Net.Sockets;
namespace SocketControl
{
public delegate void displayMessage(string msg);
/// <summary>
/// Summary description for SocketUserControl.
/// </summary>
public class SocketUserControl : System.Windows.Forms.UserControl
{
//Some required Variables
private string userID, userName;
//Flag to check if this is the first communication with the server
bool firstTime=true;
private TcpClient chatClient;
private byte[] recByte = new byte[1024];
private StringBuilder myBuilder;
private System.Windows.Forms.TextBox msgViewBox;
private System.Windows.Forms.TextBox sendBox;
private System.Windows.Forms.Button sendButton;
private System.Windows.Forms.Button connectButton;
private System.Windows.Forms.ListBox userlistBox;
private System.Windows.Forms.TextBox usernameBox;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.GroupBox groupBox2;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
public SocketUserControl()
{
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
myBuilder = new System.Text.StringBuilder();
// TODO: Add any initialization after the InitForm call
}
public void GetMsg(IAsyncResult ar)
{
int byteCount;
try
{
//Get the number of Bytes received
byteCount = (chatClient.GetStream()).EndRead(ar);
//If bytes received is less than 1 it means
//the server has disconnected
if(byteCount <1)
{
//Close the socket
Disconnect();
MessageBox.Show("Disconnected!!");
return;
}
//Send the Server message for parsing
BuildText(recByte,0,byteCount);
//Unless its the first time start Asynchronous Read
//Again
if(!firstTime)
{
AsyncCallback GetMsgCallback = new AsyncCallback(GetMsg);
(chatClient.GetStream()).BeginRead(recByte,0,1024,GetMsgCallback,this);
}
}
catch(Exception ed)
{
Disconnect();
MessageBox.Show("Exception Occured :"+ed.ToString());
}
}
public void BuildText(byte[] dataByte, int offset, int count)
{
//Loop till the number of bytes received
for(int i=offset; i<(count); i++)
{
//If a New Line character is met then
//skip the loop cycle
if(dataByte[i]==10)
continue;
//Add the Byte to the StringBuilder in Char format
myBuilder.Append(Convert.ToChar(dataByte[i]));
}
char[] spliters ={'@'};
//Check if this is the first message received
if(firstTime)
{
//Split the string received at the occurance of '@'
string[] tempString = myBuilder.ToString().Split(spliters);
//If the Server sent 'sorry' that means there was some error
//so we just disconnect the client
if(tempString[0]=="sorry")
{
object[] temp = {tempString[1]};
this.Invoke(new displayMessage(DisplayText),temp);
Disconnect();
}
else
{
//Store the Client Guid
this.userID = tempString[0];
//Loop through array of UserNames
for(int i=1;i<tempString.Length;i++)
{
object[] temp = {tempString[i]};
//Invoke the AddUser method
//Since we are working on another thread rather than the primary
//thread we have to use the Invoke method
//to call the method that will update the listbox
this.Invoke(new displayMessage(AddUser),temp);
}
//Reset the flag
firstTime=false;
//Start the listening process again
AsyncCallback GetMsgCallback = new AsyncCallback(GetMsg);
(chatClient.GetStream()).BeginRead(recByte,0,1024,GetMsgCallback,this);
}
}
else
{
//Generally all other messages get passed here
//Check if the Message starts with the ClientID
//In which case we come to know that its a Server Command
if(myBuilder.ToString().IndexOf(this.userID)>=0)
{
string[] tempString = myBuilder.ToString().Split(spliters);
//If its connected command then add the user to the ListBox
if(tempString[1]=="Connected")
{
object[] temp = {tempString[2]};
this.Invoke(new displayMessage(AddUser),temp);
}
else if(tempString[1]=="Disconnected")
{
//If its disconnected command then remove the
//username from the list box
object[] temp = {tempString[2]};
this.Invoke(new displayMessage(RemoveUser),temp);
}
}
else
{
//For regular messages append a Line terminator
myBuilder.Append("\r\n");
object[] temp = {myBuilder.ToString()};
//Invoke the DisplayText method
this.Invoke(new displayMessage(DisplayText),temp);
}
}
//Empty the StringBuilder
myBuilder = new System.Text.StringBuilder();
}
//Method to remove the user from the ListBox
private void RemoveUser(string user)
{
if(userlistBox.Items.Contains(user))
userlistBox.Items.Remove(user);
//Display the left message
DisplayText(user+" left chat\r\n");
}
//Method to Add a user to the ListBox
private void AddUser(string user)
{
if(!userlistBox.Items.Contains(user))
userlistBox.Items.Add(user);
//If not for first time then display a connected message
if(!firstTime)
DisplayText(user+" joined chat\r\n");
}
public void SendText(string msg)
{
//Get a StreamWriter
System.IO.StreamWriter chatWriter = new System.IO.StreamWriter(chatClient.GetStream());
chatWriter.WriteLine(msg);
//Flush the stream
chatWriter.Flush();
}
//Method to Display Text in the TextBox
public void DisplayText(string msg)
{
msgViewBox.AppendText(msg);
}
private void Disconnect()
{
if(chatClient!=null)
{
chatClient.Close();
chatClient=null;
}
//Reset the Buttons and Variables
userlistBox.Items.Clear();
sendButton.Enabled=false;
connectButton.Text="Connect";
usernameBox.Enabled=true;
sendBox.Enabled=false;
//this.AcceptButton=connectButton;
firstTime=true;
userID="";
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.connectButton = new System.Windows.Forms.Button();
this.label1 = new System.Windows.Forms.Label();
this.sendBox = new System.Windows.Forms.TextBox();
this.groupBox2 = new System.Windows.Forms.GroupBox();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.msgViewBox = new System.Windows.Forms.TextBox();
this.sendButton = new System.Windows.Forms.Button();
this.usernameBox = new System.Windows.Forms.TextBox();
this.userlistBox = new System.Windows.Forms.ListBox();
this.SuspendLayout();
//
// connectButton
//
this.connectButton.BackColor = System.Drawing.Color.Olive;
this.connectButton.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.connectButton.ForeColor = System.Drawing.Color.MidnightBlue;
this.connectButton.Location = new System.Drawing.Point(472, 280);
this.connectButton.Name = "connectButton";
this.connectButton.Size = new System.Drawing.Size(96, 23);
this.connectButton.TabIndex = 2;
this.connectButton.Text = "Connect";
this.connectButton.Click += new System.EventHandler(this.connectButton_Click);
//
// label1
//
this.label1.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.label1.Location = new System.Drawing.Point(165, 0);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(250, 23);
this.label1.TabIndex = 6;
this.label1.Text = "Master C# - Socket Chat Client Control";
//
// sendBox
//
this.sendBox.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.sendBox.Enabled = false;
this.sendBox.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.sendBox.ForeColor = System.Drawing.Color.Black;
this.sendBox.Location = new System.Drawing.Point(8, 280);
this.sendBox.Name = "sendBox";
this.sendBox.Size = new System.Drawing.Size(280, 20);
this.sendBox.TabIndex = 3;
this.sendBox.Text = "";
//
// groupBox2
//
this.groupBox2.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.groupBox2.Location = new System.Drawing.Point(384, 16);
this.groupBox2.Name = "groupBox2";
this.groupBox2.Size = new System.Drawing.Size(184, 256);
this.groupBox2.TabIndex = 8;
this.groupBox2.TabStop = false;
this.groupBox2.Text = "Users";
//
// groupBox1
//
this.groupBox1.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.groupBox1.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.groupBox1.Location = new System.Drawing.Point(8, 16);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(368, 256);
this.groupBox1.TabIndex = 7;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Messages";
//
// msgViewBox
//
this.msgViewBox.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.msgViewBox.ForeColor = System.Drawing.Color.Black;
this.msgViewBox.Location = new System.Drawing.Point(16, 40);
this.msgViewBox.Multiline = true;
this.msgViewBox.Name = "msgViewBox";
this.msgViewBox.ReadOnly = true;
this.msgViewBox.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.msgViewBox.Size = new System.Drawing.Size(352, 224);
this.msgViewBox.TabIndex = 0;
this.msgViewBox.TabStop = false;
this.msgViewBox.Text = "";
//
// sendButton
//
this.sendButton.BackColor = System.Drawing.Color.Olive;
this.sendButton.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.sendButton.ForeColor = System.Drawing.Color.MidnightBlue;
this.sendButton.Location = new System.Drawing.Point(296, 280);
this.sendButton.Name = "sendButton";
this.sendButton.TabIndex = 4;
this.sendButton.Text = "Send";
this.sendButton.Click += new System.EventHandler(this.sendButton_Click);
//
// usernameBox
//
this.usernameBox.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.usernameBox.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.usernameBox.ForeColor = System.Drawing.Color.Black;
this.usernameBox.Location = new System.Drawing.Point(384, 280);
this.usernameBox.Name = "usernameBox";
this.usernameBox.Size = new System.Drawing.Size(80, 20);
this.usernameBox.TabIndex = 0;
this.usernameBox.Text = "";
//
// userlistBox
//
this.userlistBox.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.userlistBox.ForeColor = System.Drawing.Color.Black;
this.userlistBox.Location = new System.Drawing.Point(392, 40);
this.userlistBox.Name = "userlistBox";
this.userlistBox.Size = new System.Drawing.Size(168, 223);
this.userlistBox.TabIndex = 20;
this.userlistBox.TabStop = false;
//
// SocketUserControl
//
this.BackColor = System.Drawing.Color.MidnightBlue;
this.Controls.AddRange(new System.Windows.Forms.Control[] {
this.connectButton,
this.usernameBox,
this.sendButton,
this.sendBox,
this.userlistBox,
this.msgViewBox,
this.groupBox1,
this.groupBox2,
this.label1});
this.ForeColor = System.Drawing.Color.Olive;
this.Name = "SocketUserControl";
this.Size = new System.Drawing.Size(580, 312);
this.ResumeLayout(false);
}
#endregion
private void sendButton_Click(object sender, System.EventArgs e)
{
if(sendBox.Text!="")
{
//Send Message
SendText(sendBox.Text);
sendBox.Text="";
}
}
private void connectButton_Click(object sender, System.EventArgs e)
{
//If user Cliked Connect
if(connectButton.Text=="Connect"&&usernameBox.Text!="")
{
try
{
//Connect to server
chatClient = new TcpClient("buddy",5151);
DisplayText("Connecting to Server ...\r\n");
//Start Reading
AsyncCallback GetMsgCallback = new AsyncCallback(GetMsg);
(chatClient.GetStream()).BeginRead(recByte,0,1024,GetMsgCallback,null);
//Send the UserName
SendText(usernameBox.Text);
this.userName=usernameBox.Text;
this.Text="Chat Client :"+userName;
usernameBox.Text="";
connectButton.Text="Disconnect";
usernameBox.Enabled=false;
sendButton.Enabled=true;
sendBox.Enabled=true;
//this.AcceptButton=sendButton;
}
catch
{
Disconnect();
MessageBox.Show("Can't connect to Server...");
}
}
else if(connectButton.Text=="Disconnect")
{
Disconnect();
}
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -