DotNET(C#) Socket基本编程

 

Socket基本编程

服务端:

using System.Net;

using System.Net.Sockets; 


using System.Text;

using System.Threading;

 


Thread mythread ;

Socket socket;


// 清理所有正在使用的资源。

protected override void Dispose( bool disposing )

{

try

  {   

   socket.Close();//释放资源

   mythread.Abort ( ) ;//中止线程

  }

  catch{ }

 

if( disposing )

{

if (components != null)

{

components.Dispose();

}

}

base.Dispose( disposing );

}

public static IPAddress GetServerIP()

{

IPHostEntry ieh=Dns.GetHostByName(Dns.GetHostName());

return ieh.AddressList[0];

}

private void BeginListen()

{

IPAddress ServerIp=GetServerIP();

IPEndPoint iep=new IPEndPoint(ServerIp,8000);

socket=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);

 

byte[] byteMessage=new byte[100];

this.label1.Text=iep.ToString();

socket.Bind(iep);

// do

while(true)

{

try

{

socket.Listen(5);

Socket newSocket=socket.Accept();

newSocket.Receive(byteMessage);

 

string sTime = DateTime.Now.ToShortTimeString ( ) ;

string msg=sTime+":"+"Message from:";

msg+=newSocket.RemoteEndPoint.ToString()+Encoding.Default.GetString(byteMessage);

this.listBox1.Items.Add(msg);

 

}

catch(SocketException ex)

{

this.label1.Text+=ex.ToString();

}

}

// while(byteMessage!=null);

}

//开始监听

private void button1_Click(object sender, System.EventArgs e)

{

try

{

mythread = new Thread(new ThreadStart(BeginListen));

mythread.Start();

 

}

catch(System.Exception er)

{

MessageBox.Show(er.Message,"完成",MessageBoxButtons.OK,MessageBoxIcon.Stop);

}

}

 

 

客户端:

 

using System.Net;

using System.Net.Sockets;

using System.Text;

 

private void button1_Click(object sender, System.EventArgs e)

{

BeginSend();

}

private void BeginSend()

{

string ip=this.txtip.Text;

string port=this.txtport.Text;

 

IPAddress serverIp=IPAddress.Parse(ip);

int serverPort=Convert.ToInt32(port);

IPEndPoint iep=new IPEndPoint(serverIp,serverPort);

byte[] byteMessage;

// do

// {

Socket socket=new Socket(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协议的接收端

 

using System.Net.Sockets ; //使用到TcpListen类

using System.Threading ; //使用到线程

using System.IO ; //使用到StreamReader类

 

int port = 8000; //定义侦听端口号

private Thread thThreadRead; //创建线程,用以侦听端口号,接收信息

private TcpListener tlTcpListen; //侦听端口号

private bool blistener = true; //设定标示位,判断侦听状态

private NetworkStream nsStream; //创建接收的基本数据流

private StreamReader srRead;

private System.Windows.Forms.StatusBar statusBar1;

private System.Windows.Forms.Button button1;

private System.Windows.Forms.ListBox listBox1; //从网络基础数据流中读取数据

private TcpClient tcClient ;

 

private void Listen ( )

{

try

{

tlTcpListen = new TcpListener ( port ) ; //以8000端口号来初始化TcpListener实例

tlTcpListen.Start ( ) ; //开始监听

statusBar1.Text = "正在监听..." ;

tcClient = tlTcpListen.AcceptTcpClient ( ) ; //通过TCP连接请求

nsStream = tcClient.GetStream ( ) ; //获取用以发送、接收数据的网络基础数据流

srRead=new StreamReader(nsStream);//以得到的网络基础数据流来初始化StreamReader实例

statusBar1.Text = "已经连接!";

 

while( blistener ) //循环侦听

{

string sMessage = srRead.ReadLine();//从网络基础数据流中读取一行数据

if ( sMessage == "STOP" ) //判断是否为断开TCP连接控制码

{

tlTcpListen.Stop(); //关闭侦听

nsStream.Close(); //释放资源

srRead.Close();

statusBar1.Text = "连接已经关闭!" ;

thThreadRead.Abort(); //中止线程

return;

}

 

string sTime = DateTime.Now.ToShortTimeString ( ) ; //获取接收数据时的时间

listBox1.Items.Add ( sTime + " " + sMessage ) ;

}

}

catch ( System.Security.SecurityException )

{

MessageBox.Show ( "侦听失败!" , "错误" ) ;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值