C#/.Net - Socket、TcpListener相关知识整理
程序员文章站
2022-04-24 22:16:44
...
学习这个类,首先需要了解基本的TCP/IP 和UDP 协议,对端口都有一定的理解……
以下是我总结的重要的几点
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();
}
}
上一篇: 总结:前端开发中让元素居中的方法
下一篇: socket相关操作(下)