【C#】 Socket通讯客户端程序
2011-12-20 10:40
323 查看
这段时间一直在优化Socket通讯这块,经常和Socket打交道,现在分享给大家一个小的案例,
代码如下:
byte[] m_dataBuffer = new byte [10];
IAsyncResult m_result;
public AsyncCallback m_pfnCallBack ;
private System.Windows.Forms.Button btnClear;
public Socket m_clientSocket;
//关闭连接
void ButtonCloseClick(object sender, System.EventArgs e)
{
if ( m_clientSocket != null )
{
m_clientSocket.Close ();
m_clientSocket = null;
}
Close();
}
//连接服务器
void ButtonConnectClick(object sender, System.EventArgs e)
{
// See if we have text on the IP and Port text fields
if(textBoxIP.Text == "" || textBoxPort.Text == ""){
MessageBox.Show("IP Address and Port Number are required to connect to the Server\n");
return;
}
try
{
UpdateControls(false);
// Create the socket instance
m_clientSocket = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp );
// Cet the remote IP address
IPAddress ip = IPAddress.Parse (textBoxIP.Text);
int iPortNo = System.Convert.ToInt16 ( textBoxPort.Text);
// Create the end point
IPEndPoint ipEnd = new IPEndPoint (ip,iPortNo);
// Connect to the remote host
m_clientSocket.Connect ( ipEnd );
if(m_clientSocket.Connected) {
UpdateControls(true);
//Wait for data asynchronously
WaitForData();
}
}
catch(SocketException se)
{
string str;
str = "\nConnection failed, is the server running?\n" + se.Message;
MessageBox.Show (str);
UpdateControls(false);
}
}
//发送消息
void ButtonSendMessageClick(object sender, System.EventArgs e)
{
try
{
string msg = richTextTxMessage.Text;
// New code to send strings
NetworkStream networkStream = new NetworkStream(m_clientSocket);
System.IO.StreamWriter streamWriter = new System.IO.StreamWriter(networkStream);
streamWriter.WriteLine(msg);
streamWriter.Flush();
}
catch(SocketException se)
{
MessageBox.Show (se.Message );
}
}
//等待接收数据
public void WaitForData()
{
try
{
if ( m_pfnCallBack == null )
{
m_pfnCallBack = new AsyncCallback (OnDataReceived);
}
SocketPacket theSocPkt = new SocketPacket ();
theSocPkt.thisSocket = m_clientSocket;
// Start listening to the data asynchronously
m_result = m_clientSocket.BeginReceive (theSocPkt.dataBuffer,
0, theSocPkt.dataBuffer.Length,
SocketFlags.None,
m_pfnCallBack,
theSocPkt);
}
catch(SocketException se)
{
MessageBox.Show (se.Message );
}
}
public class SocketPacket
{
public System.Net.Sockets.Socket thisSocket;
public byte[] dataBuffer = new byte[1024];
}
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 );
}
}
private void UpdateControls( bool connected )
{
buttonConnect.Enabled = !connected;
buttonDisconnect.Enabled = connected;
string connectStatus = connected? "Connected" : "Not Connected";
textBoxConnectStatus.Text = connectStatus;
}
void ButtonDisconnectClick(object sender, System.EventArgs e)
{
if ( m_clientSocket != null )
{
m_clientSocket.Close();
m_clientSocket = null;
UpdateControls(false);
}
}
//----------------------------------------------------
// This is a helper function used (for convenience) to
// get the IP address of the local machine
//----------------------------------------------------
String GetIP()
{
String strHostName = Dns.GetHostName();
// Find host by name
IPHostEntry iphostentry = Dns.GetHostByName(strHostName);
// Grab the first IP addresses
String IPStr = "";
foreach(IPAddress ipaddress in iphostentry.AddressList){
IPStr = ipaddress.ToString();
return IPStr;
}
return IPStr;
}
代码如下:
byte[] m_dataBuffer = new byte [10];
IAsyncResult m_result;
public AsyncCallback m_pfnCallBack ;
private System.Windows.Forms.Button btnClear;
public Socket m_clientSocket;
//关闭连接
void ButtonCloseClick(object sender, System.EventArgs e)
{
if ( m_clientSocket != null )
{
m_clientSocket.Close ();
m_clientSocket = null;
}
Close();
}
//连接服务器
void ButtonConnectClick(object sender, System.EventArgs e)
{
// See if we have text on the IP and Port text fields
if(textBoxIP.Text == "" || textBoxPort.Text == ""){
MessageBox.Show("IP Address and Port Number are required to connect to the Server\n");
return;
}
try
{
UpdateControls(false);
// Create the socket instance
m_clientSocket = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp );
// Cet the remote IP address
IPAddress ip = IPAddress.Parse (textBoxIP.Text);
int iPortNo = System.Convert.ToInt16 ( textBoxPort.Text);
// Create the end point
IPEndPoint ipEnd = new IPEndPoint (ip,iPortNo);
// Connect to the remote host
m_clientSocket.Connect ( ipEnd );
if(m_clientSocket.Connected) {
UpdateControls(true);
//Wait for data asynchronously
WaitForData();
}
}
catch(SocketException se)
{
string str;
str = "\nConnection failed, is the server running?\n" + se.Message;
MessageBox.Show (str);
UpdateControls(false);
}
}
//发送消息
void ButtonSendMessageClick(object sender, System.EventArgs e)
{
try
{
string msg = richTextTxMessage.Text;
// New code to send strings
NetworkStream networkStream = new NetworkStream(m_clientSocket);
System.IO.StreamWriter streamWriter = new System.IO.StreamWriter(networkStream);
streamWriter.WriteLine(msg);
streamWriter.Flush();
}
catch(SocketException se)
{
MessageBox.Show (se.Message );
}
}
//等待接收数据
public void WaitForData()
{
try
{
if ( m_pfnCallBack == null )
{
m_pfnCallBack = new AsyncCallback (OnDataReceived);
}
SocketPacket theSocPkt = new SocketPacket ();
theSocPkt.thisSocket = m_clientSocket;
// Start listening to the data asynchronously
m_result = m_clientSocket.BeginReceive (theSocPkt.dataBuffer,
0, theSocPkt.dataBuffer.Length,
SocketFlags.None,
m_pfnCallBack,
theSocPkt);
}
catch(SocketException se)
{
MessageBox.Show (se.Message );
}
}
public class SocketPacket
{
public System.Net.Sockets.Socket thisSocket;
public byte[] dataBuffer = new byte[1024];
}
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 );
}
}
private void UpdateControls( bool connected )
{
buttonConnect.Enabled = !connected;
buttonDisconnect.Enabled = connected;
string connectStatus = connected? "Connected" : "Not Connected";
textBoxConnectStatus.Text = connectStatus;
}
void ButtonDisconnectClick(object sender, System.EventArgs e)
{
if ( m_clientSocket != null )
{
m_clientSocket.Close();
m_clientSocket = null;
UpdateControls(false);
}
}
//----------------------------------------------------
// This is a helper function used (for convenience) to
// get the IP address of the local machine
//----------------------------------------------------
String GetIP()
{
String strHostName = Dns.GetHostName();
// Find host by name
IPHostEntry iphostentry = Dns.GetHostByName(strHostName);
// Grab the first IP addresses
String IPStr = "";
foreach(IPAddress ipaddress in iphostentry.AddressList){
IPStr = ipaddress.ToString();
return IPStr;
}
return IPStr;
}
相关文章推荐
- 【C#】 Socket通讯客户端程序
- [置顶] 【C#】 Socket通讯客户端程序
- 请教如何改善C#中socket通信机客户端程序的健壮性
- C# Socket聊天程序(一个服务端,多个客户端)
- C# Socket聊天程序(一个服务端,多个客户端)
- 请教如何改善C#中socket通信机客户端程序的健壮性
- C# SOCKET编写的简单聊天通信程序(客户端+服务端)
- 请教如何改善C#中socket通信机客户端程序的健壮性
- [C#] Socket 通讯,一个简单的聊天窗口小程序
- 服务器java客户端C#的Socket通讯遇到的坑
- 请教如何改善C#中socket通信机客户端程序的健壮性_C#教程
- C#线程池多线程Socket通讯 服务器端和客户端示例
- Socket通讯-C#客户端与Java服务端通讯(发送消息和文件)
- 请教如何改善C#中socket通信机客户端程序的健壮性_C#教程
- c# WINFORM SOCKET编程-简单聊天程序(客户端)
- C#客户端与Java程序使用socket连接并通信的兼容问题
- C# Socket聊天程序(一个服务端,多个客户端)
- Untiy中用C#实现TCP通讯(Socket通讯)服务端与客户端皆可
- C#线程池多线程Socket通讯 服务器端和客户端示例
- C#通过SOCKET与delphi 的通讯问题(一)之 字节对齐