using System;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
namespace SocketClient
{
/// <summary>
/// SocketClient 的摘要说明。
/// </summary>
public class SocketClient : System.Windows.Forms.Form
{
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Button buttonDisconnect;
private System.Windows.Forms.TextBox textBoxIP;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.Button buttonConnect;
private System.Windows.Forms.TextBox textBoxPort;
private System.Windows.Forms.RichTextBox richTextRxMessage;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.TextBox textBoxConnectStatus;
private System.Windows.Forms.RichTextBox richTextTxMessage;
private System.Windows.Forms.Button buttonSendMessage;
private System.Windows.Forms.Button buttonClose;
byte[] m_dataBuffer = new byte [10];
IAsyncResult m_result;
public AsyncCallback m_pfnCallBack ;
private System.Windows.Forms.Button btnClear;
public Socket m_clientSocket;
public delegate void UpdateRichEditCallback(string text);
public SocketClient()
{
//
// Windows 窗体设计器支持所必需的
//
InitializeComponent();
textBoxIP.Text = GetIP();
}
[STAThread]
public static void Main(string[] args)
{
Application.Run(new SocketClient());
}
#region Windows 窗体设计器生成的代码
/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.buttonClose = new System.Windows.Forms.Button();
this.buttonSendMessage = new System.Windows.Forms.Button();
this.richTextTxMessage = new System.Windows.Forms.RichTextBox();
this.textBoxConnectStatus = new System.Windows.Forms.TextBox();
this.label4 = new System.Windows.Forms.Label();
this.richTextRxMessage = new System.Windows.Forms.RichTextBox();
this.textBoxPort = new System.Windows.Forms.TextBox();
this.buttonConnect = new System.Windows.Forms.Button();
this.label5 = new System.Windows.Forms.Label();
this.textBoxIP = new System.Windows.Forms.TextBox();
this.buttonDisconnect = new System.Windows.Forms.Button();
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.btnClear = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// buttonClose
//
this.buttonClose.Location = new System.Drawing.Point(411, 233);
this.buttonClose.Name = "buttonClose";
this.buttonClose.Size = new System.Drawing.Size(77, 25);
this.buttonClose.TabIndex = 14;
this.buttonClose.Text = "关闭";
this.buttonClose.Click += new System.EventHandler(this.ButtonCloseClick);
//
// buttonSendMessage
//
this.buttonSendMessage.Location = new System.Drawing.Point(10, 198);
this.buttonSendMessage.Name = "buttonSendMessage";
this.buttonSendMessage.Size = new System.Drawing.Size(238, 26);
this.buttonSendMessage.TabIndex = 12;
this.buttonSendMessage.Text = "发送消息";
this.buttonSendMessage.Click += new System.EventHandler(this.ButtonSendMessageClick);
//
// richTextTxMessage
//
this.richTextTxMessage.Location = new System.Drawing.Point(10, 86);
this.richTextTxMessage.Name = "richTextTxMessage";
this.richTextTxMessage.Size = new System.Drawing.Size(238, 104);
this.richTextTxMessage.TabIndex = 8;
this.richTextTxMessage.Text = "";
//
// textBoxConnectStatus
//
this.textBoxConnectStatus.BackColor = System.Drawing.SystemColors.Control;
this.textBoxConnectStatus.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.textBoxConnectStatus.ForeColor = System.Drawing.SystemColors.HotTrack;
this.textBoxConnectStatus.Location = new System.Drawing.Point(72, 241);
this.textBoxConnectStatus.Name = "textBoxConnectStatus";
this.textBoxConnectStatus.ReadOnly = true;
this.textBoxConnectStatus.Size = new System.Drawing.Size(166, 14);
this.textBoxConnectStatus.TabIndex = 5;
this.textBoxConnectStatus.Text = "Not Connected";
//
// label4
//
this.label4.Location = new System.Drawing.Point(10, 69);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(110, 17);
this.label4.TabIndex = 2;
this.label4.Text = "将消息发送到服务器";
//
// richTextRxMessage
//
this.richTextRxMessage.BackColor = System.Drawing.SystemColors.InactiveCaptionText;
this.richTextRxMessage.Location = new System.Drawing.Point(256, 86);
this.richTextRxMessage.Name = "richTextRxMessage";
this.richTextRxMessage.ReadOnly = true;
this.richTextRxMessage.Size = new System.Drawing.Size(232, 138);
this.richTextRxMessage.TabIndex = 9;
this.richTextRxMessage.Text = "";
//
// textBoxPort
//
this.textBoxPort.Location = new System.Drawing.Point(104, 34);
this.textBoxPort.Name = "textBoxPort";
this.textBoxPort.Size = new System.Drawing.Size(58, 21);
this.textBoxPort.TabIndex = 7;
this.textBoxPort.Text = "8000";
//
// buttonConnect
//
this.buttonConnect.BackColor = System.Drawing.SystemColors.HotTrack;
this.buttonConnect.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.buttonConnect.ForeColor = System.Drawing.Color.Yellow;
this.buttonConnect.Location = new System.Drawing.Point(304, 7);
this.buttonConnect.Name = "buttonConnect";
this.buttonConnect.Size = new System.Drawing.Size(86, 51);
this.buttonConnect.TabIndex = 10;
this.buttonConnect.Text = "连接服务器";
this.buttonConnect.UseVisualStyleBackColor = false;
this.buttonConnect.Click += new System.EventHandler(this.ButtonConnectClick);
//
// label5
//
this.label5.Location = new System.Drawing.Point(0, 241);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(56, 17);
this.label5.TabIndex = 4;
this.label5.Text = "连接状态";
//
// textBoxIP
//
this.textBoxIP.Location = new System.Drawing.Point(104, 7);
this.textBoxIP.Name = "textBoxIP";
this.textBoxIP.Size = new System.Drawing.Size(152, 21);
this.textBoxIP.TabIndex = 6;
//
// buttonDisconnect
//
this.buttonDisconnect.BackColor = System.Drawing.Color.Red;
this.buttonDisconnect.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.buttonDisconnect.ForeColor = System.Drawing.Color.Yellow;
this.buttonDisconnect.Location = new System.Drawing.Point(401, 7);
this.buttonDisconnect.Name = "buttonDisconnect";
this.buttonDisconnect.Size = new System.Drawing.Size(87, 51);
this.buttonDisconnect.TabIndex = 11;
this.buttonDisconnect.Text = "断开服务器";
this.buttonDisconnect.UseVisualStyleBackColor = false;
this.buttonDisconnect.Click += new System.EventHandler(this.ButtonDisconnectClick);
//
// label1
//
this.label1.Location = new System.Drawing.Point(10, 9);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(86, 17);
this.label1.TabIndex = 0;
this.label1.Text = "服务器IP地址";
//
// label2
//
this.label2.Location = new System.Drawing.Point(10, 36);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(70, 17);
this.label2.TabIndex = 1;
this.label2.Text = "服务器端口";
//
// label3
//
this.label3.Location = new System.Drawing.Point(256, 69);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(128, 17);
this.label3.TabIndex = 3;
this.label3.Text = "从服务器发过来的消息";
//
// btnClear
//
this.btnClear.Location = new System.Drawing.Point(328, 233);
this.btnClear.Name = "btnClear";
this.btnClear.Size = new System.Drawing.Size(77, 25);
this.btnClear.TabIndex = 13;
this.btnClear.Text = "清空";
this.btnClear.Click += new System.EventHandler(this.btnClear_Click);
//
// SocketClient
//
this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
this.ClientSize = new System.Drawing.Size(496, 262);
this.Controls.Add(this.btnClear);
this.Controls.Add(this.buttonDisconnect);
this.Controls.Add(this.buttonSendMessage);
this.Controls.Add(this.label5);
this.Controls.Add(this.buttonClose);
this.Controls.Add(this.textBoxConnectStatus);
this.Controls.Add(this.label4);
this.Controls.Add(this.label3);
this.Controls.Add(this.buttonConnect);
this.Controls.Add(this.textBoxPort);
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);
this.Controls.Add(this.textBoxIP);
this.Controls.Add(this.richTextTxMessage);
this.Controls.Add(this.richTextRxMessage);
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "SocketClient";
this.Text = "Socket Client";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
void ButtonConnectClick(object sender, System.EventArgs e)
{
// 连接到服务器
if(textBoxIP.Text == "" || textBoxPort.Text == "")
{
MessageBox.Show("IP Address and Port Number are required to connect to the Server/n");
return;
}
try
{
UpdateControls(false);
// 建立一个socket实例
m_clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// 转换成IP路由的形式
IPAddress ip = IPAddress.Parse(textBoxIP.Text);
int iPortNo = System.Convert.ToInt16(textBoxPort.Text);
// 将网络端点表示为 IP 地址和端口号。
IPEndPoint ipEnd = new IPEndPoint(ip, iPortNo);
// 建立与远程主机的连接
m_clientSocket.Connect(ipEnd);
if(m_clientSocket.Connected)
{
UpdateControls(true);
// 等待异步传输的数据
WaitForData();
}
}
catch(SocketException se)
{
string str;
str = "Connection failed, is the server running?/n" + se.Message;
MessageBox.Show(str);
UpdateControls(false);
}
}
void ButtonDisconnectClick(object sender, System.EventArgs e)
{
// 与服务器断开连接
if (m_clientSocket != null)
{
m_clientSocket.Close();
m_clientSocket = null;
UpdateControls(false);
}
}
void ButtonSendMessageClick(object sender, System.EventArgs e)
{
// 发送消息
try
{
string msg = richTextTxMessage.Text;
// 发送字符串
NetworkStream networkStream = new NetworkStream(m_clientSocket);
System.IO.StreamWriter streamWriter = new System.IO.StreamWriter(networkStream);
streamWriter.WriteLine(msg);
streamWriter.Flush();
/* Use the following code to send bytes
byte[] byData = System.Text.Encoding.ASCII.GetBytes(objData.ToString ());
if(m_clientSocket != null){
m_clientSocket.Send (byData);
}
*/
}
catch(SocketException se)
{
MessageBox.Show(se.Message);
}
}
private void btnClear_Click(object sender, System.EventArgs e)
{
// 清空消息
richTextRxMessage.Clear();
}
void ButtonCloseClick(object sender, System.EventArgs e)
{
// 关闭窗体
if (m_clientSocket != null)
{
m_clientSocket.Close();
m_clientSocket = null;
}
Close();
}
string GetIP()
{
// 获取本机IP
string strHostName = Dns.GetHostName();
// 查找主机名
IPHostEntry iphostentry = Dns.GetHostByName(strHostName);
// 抓取第一个IP地址
string IPStr = "";
foreach(IPAddress ipaddress in iphostentry.AddressList)
{
IPStr = ipaddress.ToString();
return IPStr;
}
return IPStr;
}
private void UpdateControls( bool connected )
{
// 更新控件
buttonConnect.Enabled = !connected;
buttonDisconnect.Enabled = connected;
string connectStatus = connected? "Connected" : "Not Connected";
textBoxConnectStatus.Text = connectStatus;
}
public void WaitForData()
{
// 等待接收数据
try
{
if (m_pfnCallBack == null)
{
m_pfnCallBack = new AsyncCallback(OnDataReceived);
}
SocketPacket theSocPkt = new SocketPacket();
theSocPkt.thisSocket = m_clientSocket;
// 开始监听数据接收
m_result = m_clientSocket.BeginReceive(theSocPkt.dataBuffer,
0, theSocPkt.dataBuffer.Length,
SocketFlags.None,
m_pfnCallBack,
theSocPkt);
}
catch(SocketException se)
{
MessageBox.Show(se.Message);
}
}
//public void OnDataReceived(IAsyncResult asyn)
//{
// // 当数据到达时,接收数据
// try
// {
// SocketPacket theSockId = (SocketPacket)asyn.AsyncState;
// int iRx = theSockId.thisSocket.EndReceive(asyn);
// char[] chars = new char[iRx + 1];
// System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder();
// int charLen = d.GetChars(theSockId.dataBuffer, 0, iRx, chars, 0);
// System.String szData = new System.String(chars);
// richTextRxMessage.Text = richTextRxMessage.Text + szData;
// WaitForData();
// }
// catch (ObjectDisposedException)
// {
// System.Diagnostics.Debugger.Log(0, "1", "/nOnDataReceived: Socket has been closed/n");
// }
// catch (SocketException se)
// {
// MessageBox.Show(se.Message);
// }
//}
public void OnDataReceived(IAsyncResult asyn)
{
SocketPacket socketData = (SocketPacket)asyn.AsyncState;
int iRx = socketData.thisSocket.EndReceive(asyn);
//int iRx = theSockId.thisSocket.EndReceive(asyn);
char[] chars = new char[iRx + 1];
System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder();
int charLen = d.GetChars(socketData.dataBuffer, 0, iRx, chars, 0);
System.String szData = new System.String(chars);
richTextRxMessage.AppendText(szData);
WaitForData();
}
public class SocketPacket
{
public System.Net.Sockets.Socket thisSocket;
public byte[] dataBuffer = new byte[1024];
}
private void AppendToRichEditControl(string msg)
{
if (InvokeRequired)
{
object[] pList = {msg};
richTextRxMessage.BeginInvoke(new UpdateRichEditCallback(OnUpdateRichEdit), pList);
}
else
{
OnUpdateRichEdit(msg);
}
}
private void OnUpdateRichEdit(string msg)
{
richTextRxMessage.AppendText(msg);
}
}
}
//public void OnDataReceived(IAsyncResult asyn)
// {
// // ??????????????????
// SocketPacket socketData = (SocketPacket)asyn.AsyncState;
// try
// {
// // ??EndReceive()????BeginReceive()?????
// // ????????????????
// int iRx = socketData.m_currentSocket.EndReceive(asyn);
// char[] chars = new char[iRx + 1];
// // ??????????
// System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder();
// int charLen = d.GetChars(socketData.dataBuffer,
// 0, iRx, chars, 0);
// System.String szData = new System.String(chars);
// string msg = "" + socketData.m_clientNumber + ":";
// AppendToRichEditControl(msg + szData);
// // ????????????
// string replyMsg = "Server Reply:" + szData.ToUpper();
// // ?????byte??
// //byte[] byData = System.Text.Encoding.ASCII.GetBytes(replyMsg);
// //Socket workerSocket = (Socket)socketData.m_currentSocket;
// NetworkStream netWorkStream = new NetworkStream(m_mainSocket);
// System.IO.StreamWriter sw = new System.IO.StreamWriter(netWorkStream);
// sw.WriteLine(replyMsg);
// sw.Flush();
// //workerSocket.Send(byData);
// // ?????????
// WaitForData(socketData.m_currentSocket, socketData.m_clientNumber);
// }
// catch (ObjectDisposedException )
// {
// System.Diagnostics.Debugger.Log(0,"1","/nOnDataReceived: Socket has been closed/n");
// }
// catch(SocketException se)
// {
// if(se.ErrorCode == 10054) // ????????
// {
// // ????????
// string msg = "Client " + socketData.m_clientNumber + " Disconnected" + "/n";
// AppendToRichEditControl(msg);
// // ?worker socket????????
// m_workerSocketList[socketData.m_clientNumber - 1] = null;
// UpdateClientListControl();
// }
// else
// {
// MessageBox.Show(se.Message);
// }
// }
// }
简单的Socket聊天程序(客户端)
最新推荐文章于 2024-04-23 19:16:54 发布