电信主站 网通分站
购买流程 付款方式 常见问题 在线提问 续租服务 购物车
用户名: 密 码: 忘记密码?
首 页
域名注册
虚拟主机
双线主机
服务器租用
VPS主机
企业邮局
代理专区
客服中心
虚拟主机行业资讯 虚拟主机评测对比 互联网最新动态 技术学院 站长资讯 在线教程 网站运营
搜索优化 服务器 网络编程 图形图象 站长之家 网页制作 操作系统
冲浪宝典 软件教学 视频通信 办公软件 邮件系统 网络安全 认证考试
您当前位置:西部数码->资讯中心-> 网络编程 -> C#/CSHARP教程
c# socket编程_c#应用
作者:网友供稿 点击:0
  西部数码-全国虚拟主机10强!20余项虚拟主机管理功能,全国领先!第6代双线路虚拟主机,南北访问畅通无阻!虚拟主机可在线rar解压,自动数据恢复设置虚拟目录等.虚拟主机免费赠送访问统计,企业邮局.Cn域名注册10元/年,自助建站480元起,免费试用7天,满意再付款!P4主机租用799元/月.月付免压金!
文章页数:[1] 

//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 ( "侦听失败!" , "错误" ) ;

}

}

//开始监听

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

{

thThreadRead = new Thread ( new ThreadStart ( Listen ) );

thThreadRead.Start();//启动线程

button1.Enabled=false;

}

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

protected override void Dispose( bool disposing )

{

try

{

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

nsStream.Close();

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

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

}

catch{}

 

if( disposing )

{

if (components != null)

{

components.Dispose();

}

}

base.Dispose( disposing );

}

 

TCP协议的发送端

 

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

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

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

using System.Net; //使用IPAddress类、IPHostEntry类等

 

private StreamWriter swWriter; //用以向网络基础数据流传送数据 

private NetworkStream nsStream; //创建发送数据的网络基础数据流 

private TcpClient tcpClient;

private System.Windows.Forms.Button button1;

private System.Windows.Forms.TextBox textBox1;

private System.Windows.Forms.Button button2;

private System.Windows.Forms.TextBox textBox2;

private System.Windows.Forms.StatusBar statusBar1;

private System.Windows.Forms.Label label1;

private System.Windows.Forms.Label label2; //通过它实现向远程主机提出TCP连接申请 

private bool tcpConnect = false; //定义标识符,用以表示TCP连接是否建立

 

//连接 

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

{

IPAddress ipRemote ;

try

{

ipRemote = IPAddress.Parse ( textBox1.Text ) ;

}

catch //判断给定的IP地址的合法性

{

MessageBox.Show ( "输入的IP地址不合法!" , "错误提示!" ) ;

return ;

}

 

IPHostEntry ipHost ;

try

{

ipHost = Dns.Resolve ( textBox1.Text ) ; 

}

catch //判断IP地址对应主机是否在线

{

MessageBox.Show ("远程主机不在线!" , "错误提示!" ) ;

return ;

}

 

string sHostName = ipHost.HostName ;

try

{

TcpClient tcpClient = new TcpClient(sHostName,8000);//对远程主机的8000端口提出TCP连接申请

nsStream = tcpClient.GetStream();//通过申请,并获取传送数据的网络基础数据流  

swWriter = new StreamWriter(nsStream);//使用获取的网络基础数据流来初始化StreamWriter实例

button1.Enabled = false ;

button2.Enabled = true ;

tcpConnect = true ;

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

}

catch

{

MessageBox.Show ( "无法和远程主机8000端口建立连接!" , "错误提示!" ) ;

return ;

}

}

 

//发送

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

{

if (textBox2.Text !="")

{

swWriter.WriteLine(textBox2.Text);//刷新当前数据流中的数据

swWriter.Flush();

}

else

{

MessageBox.Show("发送信息不能为空!","错误提示!");

}

}

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

protected override void Dispose( bool disposing )

{

if ( tcpConnect )

{

swWriter.WriteLine ( "STOP" ) ; //发送控制码  

swWriter.Flush (); //刷新当前数据流中的数据  

nsStream.Close (); //清除资源

swWriter.Close ();

}

if( disposing )

{

if (components != null)

{

components.Dispose();

}

}

base.Dispose( disposing );

}


文章整理:西部数码--专业提供域名注册虚拟主机服务
http://www.west263.com
以上信息与文章正文是不可分割的一部分,如果您要转载本文章,请保留以上信息,谢谢!
相关主题
文章页数:[1] 
Google
热门文章
·c#程序模拟鼠标操作 [simulate mouse movement and click programmatically] _c#应用
·用c#写的asp+域名查询程序_c#应用
·c#.net网络程序开发-socket篇 _c#应用
·c# socket编程_c#应用
·c#和vb.net语法对比图_c#教程
·c#的四个基本技巧 _c#教程
·c#基础—关于类 _c#教程
·漫谈c#编程中的多态与new关键字_c#教程
·c# namespace_c#教程
·c# 正确读取存储中文,以及如何获取字节流编码_c#应用

最新文章
·利用c#远程存取access数据库_c#应用
·c# 3.0新特性系列:隐含类型var_c#教程
·c#动态生成树型结构的web程序设计_c#应用
·论c#变得越来越臃肿是不可避免的_c#应用
·用c#监控并显示cpu状态信息_c#应用
·c#中实现vb中的createobject方法_c#应用
·photoshop给花瓶打造彩绘效果_photoshop教程
·使用c#创建sql server的存储过程_c#应用
·c#数据库操作的3种典型用法_c#应用
·c#调用oracle存储过程返回结果集及函数_c#应用


 
 


版权申明:本站文章均来自网络,如有侵权,请联系我们,我们收到后立即删除,谢谢!

特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有。
  打印  刷新  关闭
返回首页 |关于我们 | 联系我们 | 付款方式 | 创业联盟 | 虚拟主机 | 资讯中心 | 友情链接 | 网站地图

版权所有 西部数码(www.west263.com)
CopyRight (c) 2002~2006 west263.com all right reserved.
公司地址:四川成都市万和路90号天象大厦4楼 邮编:610031
电话总机:028-86262244 86263048 86263408 86263960 86264018 86267838
售前咨询:总机转201 202 203 204 206 208
售后服务:总机转211 212 213 214
财务咨询:总机转224 223 传真:028-86264041 财务QQ:点击发送消息给对方635483282
售前咨询QQ:点击发送消息给对方2182518 点击发送消息给对方241975952 点击发送消息给对方275026793 点击发送消息给对方408235859
售后服务QQ:点击发送消息给对方17708515 点击发送消息给对方307742704 点击发送消息给对方287976517 点击发送消息给对方363783715
《中华人民共和国增值电信业务经营许可证》编号:川B2-20030065号