日期:2014-05-18  浏览次数:20953 次

再开一帖:Socket监听与TcpListener监听区别与用法
1、两个分别在什么情况下使用。
2、就是在远程控制中,什么情况下该用Socket监听,什么情况下该用TcpListener监听。
3、他们两个的区别在什么地方。
4、可否提供一些源码例子?
5、初学Socket,多多包含,100分送上。

------解决方案--------------------
真有意思,这就好像把蔬菜带着泥土刷洗一下就给你吃你就认得,做成下酒菜你就不认得了?!

TcpListener是对Socket的封装,使得你编程时更加专注于要解决的问题。
------解决方案--------------------
学习这个类,首先需要了解基本的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[] m