这段时间一直在优化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;
}
分享到:
相关推荐
C#利用Socket实现客户端之间直接通信 实验功能: 设计程序,分别构建通信的两端:服务器端和客户端应用程序,套接字类型为面向连接的Socket,自己构建双方的应答模式,实现双方的数据的发送和接收(S发给C,C发给S)...
本实例包含: 1. C# SOCKET同步通讯实例的服务端和客户端端程序 2. C# SOCKET异步通讯实例的服务端和客户端端程序 需要用到胡知识点有:多线程 和 委托
C#基于socket通讯客户端,简单的客户端程序。
使用C#语言编写的Socket通信客户端和服务端应用程序,实现客户端和服务端的网络通信。
C# SOCKET网络通信程序(客户端+服务端),可以方便的调试协议.源码可执行.
C# socket网络通讯示例程序,示例代码中一个是服务端,另一个客户端。本示例是学习socket通讯技术入门的最好示例。
C# 3.0 socket通讯程序有服务器端和客户端2个程序例子,非常实用
c#语言开发多线程socket服务器端程序,实现一个服务器同时与多个客户端连接对话。
C# 用socket协议编写的服务器和客户端通信的小程序
用于客户端和服务器端的通讯,SOcket通讯是必不可少;
根据查找的一些socket通讯程序,自己写了一个简单的例子,一个服务器可对应多个客户端,测试过20个客户端,程序正常!
基于socket的TCPIP通讯,C#开发,有客户端及服务端,具备多服务端单客户端运行模式,演示demo
C#聊天 SOCKET通讯程序 服务端 客户端 多线程 委托、事件
C#解决socket通信过程中粘包分包问题,本项目是一个只有6个C#代码文件的开源小工程,用来学习基于TCP的套接字通信包,可以自定义通信协议,处理分包和粘包,内置一个服务端和客户端的套接字程序,也有测试代码和对应...
本程序在VS2005中测试通过。内有使用说明。可发送接受中文。
C# Socket Udp 通信服务器端(控制台应用程序),不可多的的Udp资料。本地端口10000
用C#窗体界面程序实现客户端和服务器的通讯,用到套接字socket。
基于C#控制台应用程序,通过TCP SOCKET 实现简单的客户端服务器通讯功能,服务器接收到客户端发来的信息,并返回信息给客户端。
socket客户端代码,使用c#完成,配合socket服务端一起试用,代码还不够成熟,有待优化,但是本人测试没有问题,可参考用于实现C/S系统的即时通讯系统
服务器与客户端互传信息的Socket 例子 该通讯程序已经在实际项目中运营过,代码是非常不错的。 功能有:上传下载、消息请求访问服务器目标、文件夹、文件。能够满足一般的通讯要求