C# socket

  1. //服务端:
  2. using System.Net;
  3. using System.Net.Sockets;
  4. using System.Text;
  5. using System.Threading;
  6. Thread mythread ;
  7. Socket socket;
  8. // 清理所有正在使用的资源。
  9. protected override void Dispose( bool disposing )
  10. {
  11. try
  12.   {   
  13.    socket.Close();//释放资源
  14.    mythread.Abort ( ) ;//中止线程
  15.   }
  16.   catch{ }
  17. if( disposing )
  18. {
  19. if (components != null)
  20. {
  21. components.Dispose();
  22. }
  23. }
  24. base.Dispose( disposing );
  25. }
  26. public static IPAddress GetServerIP()
  27. {
  28. IPHostEntry ieh=Dns.GetHostByName(Dns.GetHostName());
  29. return ieh.AddressList[0];
  30. }
  31. private void BeginListen()
  32. {
  33. IPAddress ServerIp=GetServerIP();
  34. IPEndPoint iep=new IPEndPoint(ServerIp,8000);
  35. socket=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
  36. byte[] byteMessage=new byte[100];
  37. this.label1.Text=iep.ToString();
  38. socket.Bind(iep);
  39. // do
  40. while(true)
  41. {
  42. try
  43. {
  44. socket.Listen(5);
  45. Socket newSocket=socket.Accept();
  46. newSocket.Receive(byteMessage);
  47. string sTime = DateTime.Now.ToShortTimeString ( ) ;
  48. string msg=sTime+":"+"Message from:";
  49. msg+=newSocket.RemoteEndPoint.ToString()+Encoding.Default.GetString(byteMessage);
  50. this.listBox1.Items.Add(msg);
  51. }
  52. catch(SocketException ex)
  53. {
  54. this.label1.Text+=ex.ToString();
  55. }
  56. }
  57. // while(byteMessage!=null);
  58. }
  59. //开始监听
  60. private void button1_Click(object sender, System.EventArgs e)
  61. {
  62. try
  63. {
  64. mythread = new Thread(new ThreadStart(BeginListen));
  65. mythread.Start();
  66. }
  67. catch(System.Exception er)
  68. {
  69. MessageBox.Show(er.Message,"完成",MessageBoxButtons.OK,MessageBoxIcon.Stop);
  70. }
  71. }
  72. ********************************************************
  73. //客户端:
  74.  using System.Net;
  75. using System.Net.Sockets;
  76. using System.Text;
  77. private void button1_Click(object sender, System.EventArgs e)
  78. {
  79. BeginSend();
  80. }
  81. private void BeginSend()
  82. {
  83. string ip=this.txtip.Text;
  84. string port=this.txtport.Text;
  85. IPAddress serverIp=IPAddress.Parse(ip);
  86. int serverPort=Convert.ToInt32(port);
  87. IPEndPoint iep=new IPEndPoint(serverIp,serverPort);
  88. byte[] byteMessage;
  89. // do
  90. // {
  91. Socket socket=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
  92. socket.Connect(iep);
  93. byteMessage=Encoding.ASCII.GetBytes(textBox1.Text);
  94. socket.Send(byteMessage);
  95. socket.Shutdown(SocketShutdown.Both);
  96. socket.Close();
  97. // }
  98. // while(byteMessage!=null);
  99. }
  100. 基于TCP协议的发送和接收端
  101. TCP协议的接收端
  102. using System.Net.Sockets ; //使用到TcpListen类
  103. using System.Threading ; //使用到线程
  104. using System.IO ; //使用到StreamReader类
  105. int port = 8000; //定义侦听端口号
  106. private Thread thThreadRead; //创建线程,用以侦听端口号,接收信息
  107. private TcpListener tlTcpListen; //侦听端口号
  108. private bool blistener = true//设定标示位,判断侦听状态
  109. private NetworkStream nsStream; //创建接收的基本数据流
  110. private StreamReader srRead;
  111. private System.Windows.Forms.StatusBar statusBar1;
  112. private System.Windows.Forms.Button button1;
  113. private System.Windows.Forms.ListBox listBox1; //从网络基础数据流中读取数据
  114. private TcpClient tcClient ;
  115. private void Listen ( )
  116. {
  117. try
  118. {
  119. tlTcpListen = new TcpListener ( port ) ; //以8000端口号来初始化TcpListener实例
  120. tlTcpListen.Start ( ) ; //开始监听
  121. statusBar1.Text = "正在监听" ;
  122. tcClient = tlTcpListen.AcceptTcpClient ( ) ; //通过TCP连接请求
  123. nsStream = tcClient.GetStream ( ) ; //获取用以发送、接收数据的网络基础数据流
  124. srRead=new StreamReader(nsStream);//以得到的网络基础数据流来初始化StreamReader实例
  125. statusBar1.Text = "已经连接!";
  126.  while( blistener ) //循环侦听
  127. {
  128. string sMessage = srRead.ReadLine();//从网络基础数据流中读取一行数据
  129. if ( sMessage == "STOP" ) //判断是否为断开TCP连接控制码
  130. {
  131. tlTcpListen.Stop(); //关闭侦听
  132. nsStream.Close(); //释放资源
  133. srRead.Close();
  134. statusBar1.Text = "连接已经关闭!" ;
  135. thThreadRead.Abort(); //中止线程
  136. return;
  137. }
  138. string sTime = DateTime.Now.ToShortTimeString ( ) ; //获取接收数据时的时间
  139. listBox1.Items.Add ( sTime + " " + sMessage ) ;
  140. }
  141. }
  142. catch ( System.Security.SecurityException )
  143. {
  144. MessageBox.Show ( "侦听失败!" , "错误" ) ;
  145. }
  146. }
  147. //开始监听
  148. private void button1_Click(object sender, System.EventArgs e)
  149. {
  150. thThreadRead = new Thread ( new ThreadStart ( Listen ) );
  151. thThreadRead.Start();//启动线程
  152. button1.Enabled=false;
  153. }
  154. // 清理所有正在使用的资源。
  155. protected override void Dispose( bool disposing )
  156. {
  157. try
  158. {
  159. tlTcpListen.Stop(); //关闭侦听
  160. nsStream.Close();
  161. srRead.Close();//释放资源
  162. thThreadRead.Abort();//中止线程
  163. }
  164. catch{}
  165. if( disposing )
  166. {
  167. if (components != null)
  168. {
  169. components.Dispose();
  170. }
  171. }
  172. base.Dispose( disposing );
  173. }
  174. TCP协议的发送端
  175. using System.Net.Sockets; //使用到TcpListen类
  176. using System.Threading; //使用到线程
  177. using System.IO; //使用到StreamWriter类
  178. using System.Net; //使用IPAddress类、IPHostEntry类等
  179. private StreamWriter swWriter; //用以向网络基础数据流传送数据 
  180. private NetworkStream nsStream; //创建发送数据的网络基础数据流 
  181. private TcpClient tcpClient;
  182. private System.Windows.Forms.Button button1;
  183. private System.Windows.Forms.TextBox textBox1;
  184. private System.Windows.Forms.Button button2;
  185. private System.Windows.Forms.TextBox textBox2;
  186. private System.Windows.Forms.StatusBar statusBar1;
  187. private System.Windows.Forms.Label label1;
  188. private System.Windows.Forms.Label label2; //通过它实现向远程主机提出TCP连接申请 
  189. private bool tcpConnect = false//定义标识符,用以表示TCP连接是否建立
  190. //连接 
  191. private void button1_Click(object sender, System.EventArgs e)
  192. {
  193. IPAddress ipRemote ;
  194. try
  195. {
  196. ipRemote = IPAddress.Parse ( textBox1.Text ) ;
  197. }
  198. catch //判断给定的IP地址的合法性
  199. {
  200. MessageBox.Show ( "输入的IP地址不合法!" , "错误提示!" ) ;
  201. return ;
  202. }
  203. IPHostEntry ipHost ;
  204. try
  205. {
  206. ipHost = Dns.Resolve ( textBox1.Text ) ; 
  207. }
  208. catch //判断IP地址对应主机是否在线
  209. {
  210. MessageBox.Show ("远程主机不在线!" , "错误提示!" ) ;
  211. return ;
  212. }
  213. string sHostName = ipHost.HostName ;
  214. try
  215. {
  216. TcpClient tcpClient = new TcpClient(sHostName,8000);//对远程主机的8000端口提出TCP连接申请
  217. nsStream = tcpClient.GetStream();//通过申请,并获取传送数据的网络基础数据流  
  218. swWriter = new StreamWriter(nsStream);//使用获取的网络基础数据流来初始化StreamWriter实例
  219. button1.Enabled = false ;
  220. button2.Enabled = true ;
  221. tcpConnect = true ;
  222. statusBar1.Text = "已经连接!" ;
  223. }
  224. catch
  225. {
  226. MessageBox.Show ( "无法和远程主机8000端口建立连接!" , "错误提示!" ) ;
  227. return ;
  228. }
  229. }
  230. //发送
  231. private void button2_Click(object sender, System.EventArgs e)
  232. {
  233. if (textBox2.Text !="")
  234. {
  235. swWriter.WriteLine(textBox2.Text);//刷新当前数据流中的数据
  236. swWriter.Flush();
  237. }
  238. else
  239. {
  240. MessageBox.Show("发送信息不能为空!","错误提示!");
  241. }
  242. }
  243. // 清理所有正在使用的资源。
  244. protected override void Dispose( bool disposing )
  245. {
  246. if ( tcpConnect )
  247. {
  248. swWriter.WriteLine ( "STOP" ) ; //发送控制码  
  249. swWriter.Flush (); //刷新当前数据流中的数据  
  250. nsStream.Close (); //清除资源
  251. swWriter.Close ();
  252. }
  253. if( disposing )
  254. {
  255. if (components != null)
  256. {
  257. components.Dispose();
  258. }
  259. }
  260. base.Dispose( disposing );
  261. }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值