C#/.Net - Socket、TcpListener相关知识整理

1 篇文章 0 订阅

学习这个类,首先需要了解基本的TCP/IP 和UDP 协议,对端口都有一定的理解……

以下是我总结的重要的几点


1.利用Tcp协议编程
1)服务器端:
     a)建立TCP监听器TcpListener对象。
                   TcpListener tl=new TcpListener(端口号);
     b)启动监听器
                    tl.Start();
     c)用监听器获取连接进来的套接字(Socket)
                    Socket s=myList.AcceptSocket();
     d)通过Socket的Receive方法获取客户端发送的数据
                   byte [] result=new byte[1024];
                   int k=s.Receive(result);
      e)通过Socket的Send方法向客户端发送数据
                    byte[] st=System.Text.Encoding.Default.GetBytes(“text”);
                    s.Send(st);
      f)在通讯结束后,需要释放资源结束监听
                    s.Close();
                    tl.Stop();
2)客户端:
     a)建立TCP客户端TcpClient对象。
                    TcpClient tcpclnt = new TcpClient();
     b)连接服务器
                      tcpclnt.Connect(IP地址字符串,端口号);
     c)获得客户端网络传输 流
                      Stream stm =tcpclnt.GetStream();
     d)通过Stream的Write方法向服务器端发送的数据
     e)通过Stream的Read方法读取服务器段发来的数据
     f)在通讯结束后,需要释放资源,结束和服务器的连接
                      tcpclnt.Close();
2.利用UDP协议编程
a)建立UDP客户端UdpClient对象。
         UdpClient uc=new UdpClient(端口号);
b)连接对方远程主机
         uc.Connect(IP地址,对方远程主机的端口号);
c)通过uc的Receive方法获取远程主机发送来的数据
    IPEndPoint ip=new IPEndPoint(IPAddress.Parse(IP字符串),端口号);
    byte[] b=uc.Receive(ref ip);
e)通过uc的Send方法向远程主机发送数据
          byte[] st=System.Text.Encoding.Default.GetBytes(“text”);
          uc.Send(st);
f)在通讯结束后,需要释放资源
          uc.Close(); 


如果你已在此地址上做了发送数据的socket或tcpclient或udp,那么这个监听和发送在同一个端口上就会发生错误的。

using System; 
using System.IO; 
using System.Net; 
using System.Net.Sockets; 
using System.Text; 


class MyTcpListener 
{ 
public static void Main() 
{ 
TcpListener server=null; 
try 
{ 
// Set the TcpListener on port 13000. 
Int32 port = 13000; 
IPAddress localAddr = IPAddress.Parse("127.0.0.1"); 


// TcpListener server = new TcpListener(port); 
server = new TcpListener(localAddr, port); 


// Start listening for client requests. 
server.Start(); 


// Buffer for reading data 
Byte[] bytes = new Byte[256]; 
String data = null; 


// Enter the listening loop. 
while(true) 
{ 
Console.Write("Waiting for a connection... "); 


// Perform a blocking call to accept requests. 
// You could also user server.AcceptSocket() here. 
TcpClient client = server.AcceptTcpClient(); 
Console.WriteLine("Connected!"); 


data = null; 


// Get a stream object for reading and writing 
NetworkStream stream = client.GetStream(); 


int i; 


// Loop to receive all the data sent by the client. 
while((i = stream.Read(bytes, 0, bytes.Length))!=0) 
{ 
// Translate data bytes to a ASCII string. 
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i); 
Console.WriteLine("Received: {0}", data); 


// Process the data sent by the client. 
data = data.ToUpper(); 


byte[] msg = System.Text.Encoding.ASCII.GetBytes(data); 


// Send back a response. 
stream.Write(msg, 0, msg.Length); 
Console.WriteLine("Sent: {0}", data); 
} 


// Shutdown and end connection 
client.Close(); 
} 
} 
catch(SocketException e) 
{ 
Console.WriteLine("SocketException: {0}", e); 
} 
finally 
{ 
// Stop listening for new clients. 
server.Stop(); 
} 




Console.WriteLine("\nHit enter to continue..."); 
Console.Read(); 
} 
} 


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值