C#SOCKET例子.docx
《C#SOCKET例子.docx》由会员分享,可在线阅读,更多相关《C#SOCKET例子.docx(36页珍藏版)》请在冰豆网上搜索。
C#SOCKET例子
//Socket基本编程
//服务端:
usingSystem.Net;
usingSystem.Net.Sockets;
usingSystem.Text;
usingSystem.Threading;
Threadmythread;
Socketsocket;
//清理所有正在使用的资源。
protectedoverridevoidDispose(booldisposing)
{
try
{
socket.Close();//释放资源
mythread.Abort();//中止线程
}
catch{}
if(disposing)
{
if(components!
=null)
{
components.Dispose();
}
}
base.Dispose(disposing);
}
publicstaticIPAddressGetServerIP()
{
IPHostEntryieh=Dns.GetHostByName(Dns.GetHostName());
returnieh.AddressList[0];
}
privatevoidBeginListen()
{
IPAddressServerIp=GetServerIP();
IPEndPointiep=newIPEndPoint(ServerIp,8000);
socket=newSocket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
byte[]byteMessage=newbyte[100];
this.label1.Text=iep.ToString();
socket.Bind(iep);
//do
while(true)
{
try
{
socket.Listen(5);
SocketnewSocket=socket.Accept();
newSocket.Receive(byteMessage);
stringsTime=DateTime.Now.ToShortTimeString();
stringmsg=sTime+":
"+"Messagefrom:
";
msg+=newSocket.RemoteEndPoint.ToString()+Encoding.Default.GetString(byteMessage);
this.listBox1.Items.Add(msg);
}
catch(SocketExceptionex)
{
this.label1.Text+=ex.ToString();
}
}
//while(byteMessage!
=null);
}
//开始监听
privatevoidbutton1_Click(objectsender,System.EventArgse)
{
try
{
mythread=newThread(newThreadStart(BeginListen));
mythread.Start();
}
catch(System.Exceptioner)
{
MessageBox.Show(er.Message,"完成",MessageBoxButtons.OK,MessageBoxIcon.Stop);
}
}
//客户端:
usingSystem.Net;
usingSystem.Net.Sockets;
usingSystem.Text;
privatevoidbutton1_Click(objectsender,System.EventArgse)
{
BeginSend();
}
privatevoidBeginSend()
{
stringip=this.txtip.Text;
stringport=this.txtport.Text;
IPAddressserverIp=IPAddress.Parse(ip);
intserverPort=Convert.ToInt32(port);
IPEndPointiep=newIPEndPoint(serverIp,serverPort);
byte[]byteMessage;
//do
//{
Socketsocket=newSocket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
socket.Connect(iep);
byteMessage=Encoding.ASCII.GetBytes(textBox1.Text);
socket.Send(byteMessage);
socket.Shutdown(SocketShutdown.Both);
socket.Close();
//}
//while(byteMessage!
=null);
}
基于TCP协议的发送和接收端
TCP协议的接收端
usingSystem.Net.Sockets;//使用到TcpListen类
usingSystem.Threading;//使用到线程
usingSystem.IO;//使用到StreamReader类
intport=8000;//定义侦听端口号
privateThreadthThreadRead;//创建线程,用以侦听端口号,接收信息
privateTcpListenertlTcpListen;//侦听端口号
privateboolblistener=true;//设定标示位,判断侦听状态
privateNetworkStreamnsStream;//创建接收的基本数据流
privateStreamReadersrRead;
privateSystem.Windows.Forms.StatusBarstatusBar1;
privateSystem.Windows.Forms.Buttonbutton1;
privateSystem.Windows.Forms.ListBoxlistBox1;//从网络基础数据流中读取数据
privateTcpClienttcClient;
privatevoidListen()
{
try
{
tlTcpListen=newTcpListener(port);//以8000端口号来初始化TcpListener实例
tlTcpListen.Start();//开始监听
statusBar1.Text="正在监听";
tcClient=tlTcpListen.AcceptTcpClient();//通过TCP连接请求
nsStream=tcClient.GetStream();//获取用以发送、接收数据的网络基础数据流
srRead=newStreamReader(nsStream);//以得到的网络基础数据流来初始化StreamReader实例
statusBar1.Text="已经连接!
";
while(blistener)//循环侦听
{
stringsMessage=srRead.ReadLine();//从网络基础数据流中读取一行数据
if(sMessage=="STOP")//判断是否为断开TCP连接控制码
{
tlTcpListen.Stop();//关闭侦听
nsStream.Close();//释放资源
srRead.Close();
statusBar1.Text="连接已经关闭!
";
thThreadRead.Abort();//中止线程
return;
}
stringsTime=DateTime.Now.ToShortTimeString();//获取接收数据时的时间
listBox1.Items.Add(sTime+""+sMessage);
}
}
catch(System.Security.SecurityException)
{
MessageBox.Show("侦听失败!
","错误");
}
}
//开始监听
privatevoidbutton1_Click(objectsender,System.EventArgse)
{
thThreadRead=newThread(newThreadStart(Listen));
thThreadRead.Start();//启动线程
button1.Enabled=false;
}
//清理所有正在使用的资源。
protectedoverridevoidDispose(booldisposing)
{
try
{
tlTcpListen.Stop();//关闭侦听
nsStream.Close();
srRead.Close();//释放资源
thThreadRead.Abort();//中止线程
}
catch{}
if(disposing)
{
if(components!
=null)
{
components.Dispose();
}
}
base.Dispose(disposing);
}
TCP协议的发送端
usingSystem.Net.Sockets;//使用到TcpListen类
usingSystem.Threading;//使用到线程
usingSystem.IO;//使用到StreamWriter类
usingSystem.Net;//使用IPAddress类、IPHostEntry类等
privateStreamWriterswWriter;//用以向网络基础数据流传送数据
privateNetworkStreamnsStream;//创建发送数据的网络基础数据流
privateTcpClienttcpClient;
privateSystem.Windows.Forms.Buttonbutton1;
privateSystem.Windows.Forms.TextBoxtextBox1;
privateSystem.Windows.Forms.Buttonbutton2;
privateSystem.Windows.Forms.TextBoxtextBox2;
privateSystem.Windows.Forms.StatusBarstatusBar1;
privateSystem.Windows.Forms.Labellabel1;
privateSystem.Windows.Forms.Labellabel2;//通过它实现