MS还为我们提供了几个助手类:TcpClient类、TcpListener类、UDPClient类。这几个类简化了一些操作
以下是原生c#的原生socket编写上述服务
tcp_socket
server
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace tcpserver
{
/// <summary>
/// Class1 的摘要说明。
/// </summary>
class server
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main(string[] args)
{
//
// TODO: 在此处添加代码以启动应用程序
//
int recv;//用于表示客户端发送的信息长度
byte[] data=new byte[1024];//用于缓存客户端所发送的信息,通过socket传递的信息必须为字节数组
IPEndPoint ipep=new IPEndPoint(IPAddress.Any,9050);//本机预使用的IP和端口
Socket newsock=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
newsock.Bind(ipep);//绑定
newsock.Listen(10);//监听
Console.WriteLine("waiting for a client");
Socket client=newsock.Accept();//当有可用的客户端连接尝试时执行,并返回一个新的socket,用于与客户端之间的通信
IPEndPoint clientip=(IPEndPoint)client.RemoteEndPoint;
Console.WriteLine("connect with client:"+clientip.Address+" at port:"+clientip.Port);
string welcome="welcome here!";
data=Encoding.ASCII.GetBytes(welcome);
client.Send(data,data.Length,SocketFlags.None);//发送信息
while(true)
{//用死循环来不断的从客户端获取信息
data=new byte[1024];
recv=client.Receive(data);
Console.WriteLine("recv="+recv);
if (recv==0)//当信息长度为0,说明客户端连接断开
break;
Console.WriteLine(Encoding.ASCII.GetString(data,0,recv));
client.Send(data,recv,SocketFlags.None);
}
Console.WriteLine("Disconnected from"+clientip.Address);
client.Close();
newsock.Close();
}
}
}
client
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace tcpclient
{
/// <summary>
/// Class1 的摘要说明。
/// </summary>
class client
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main(string[] args)
{
//
// TODO: 在此处添加代码以启动应用程序
//
byte[] data=new byte[1024];
Socket newclient=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
Console.Write("please input the server ip:");
string ipadd=Console.ReadLine();
Console.WriteLine();
Console.Write("please input the server port:");
int port=Convert.ToInt32(Console.ReadLine());
IPEndPoint ie=new IPEndPoint(IPAddress.Parse(ipadd),port);//服务器的IP和端口
try
{
//因为客户端只是用来向特定的服务器发送信息,所以不需要绑定本机的IP和端口。不需要监听。
newclient.Connect(ie);
}
catch(SocketException e)
{
Console.WriteLine("unable to connect to server");
Console.WriteLine(e.ToString());
return;
}
int recv = newclient.Receive(data);
string stringdata=Encoding.ASCII.GetString(data,0,recv);
Console.WriteLine(stringdata);
while(true)
{
string input=Console.ReadLine();
if(input=="exit")
break;
newclient.Send(Encoding.ASCII.GetBytes(input));
data=new byte[1024];
recv=newclient.Receive(data);
stringdata=Encoding.ASCII.GetString(data,0,recv);
Console.WriteLine(stringdata);
}
Console.WriteLine("disconnect from sercer");
newclient.Shutdown(SocketShutdown.Both);
newclient.Close();
}
}
}
udp_socket
server
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace SimpleUdpSrvr
{
class Program
{
static void Main(string[] args)
{
int recv;
byte[] data = new byte[1024];
IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9050);//定义一网络端点
Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);//定义一个Socket
newsock.Bind(ipep);//Socket与本地的一个终结点相关联
Console.WriteLine("Waiting for a client..");
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);//定义要发送的计算机的地址
EndPoint Remote = (EndPoint)(sender);//
recv = newsock.ReceiveFrom(data, ref Remote);//接受数据
Console.WriteLine("Message received from{0}:", Remote.ToString());
Console.WriteLine(Encoding.ASCII.GetBytes(data,0,recv));
string welcome = "Welcome to my test server!";
data = Encoding.ASCII.GetBytes(welcome);
newsock.SendTo(data, data.Length, SocketFlags.None, Remote);
while (true)
{
data = new byte[1024];
recv = newsock.ReceiveFrom(data, ref Remote);
Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
newsock.SendTo(data, recv, SocketFlags.None, Remote);
}
}
}
}
client
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace SimpleUdpClient
{
class Program
{
static void Main(string[] args)
{
byte[] data = new byte[1024];//定义一个数组用来做数据的缓冲区
string input, stringData;
IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9050);
Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
string welcome = "Hello,are you there?";
data = Encoding.ASCII.GetBytes(welcome);
server.SendTo(data, data.Length, SocketFlags.None, ipep);//将数据发送到指定的终结点
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
EndPoint Remote = (EndPoint)sender;
data = new byte[1024];
int recv = server.ReceiveFrom(data, ref Remote);//接受来自服务器的数据
Console.WriteLine("Message received from{0}:", Remote.ToString());
Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
while (true)//读取数据
{
input = Console.ReadLine();//从键盘读取数据
if (input == "text")//结束标记
{
break;
}
server.SendTo(Encoding.ASCII.GetBytes(input), Remote);//将数据发送到指定的终结点Remote
data = new byte[1024];
recv = server.ReceiveFrom(data, ref Remote);//从Remote接受数据
stringData = Encoding.ASCII.GetString(data, 0, recv);
Console.WriteLine(stringData);
}
Console.WriteLine("Stopping client");
server.Close();
}
}
}
unix_socket
using System;
using System.Net.Sockets;
using System.Threading.Tasks;
class Program
{
static void Main(string[] args)
{
var path = "/tmp/foo.sock";
// client
Task.Run(async () =>
{
// wait 2 seconds
await Task.Delay(2000);
using (var socket = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified))
{
socket.Connect(new UnixDomainSocketEndPoint(path));
// send hello world
var dataToSend = System.Text.Encoding.UTF8.GetBytes("Hello-world!");
socket.Send(dataToSend);
}
});
// Server
{
// delete file if it exists
if (System.IO.File.Exists(path))
System.IO.File.Delete(path);
var socket = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified);
socket.Bind(new UnixDomainSocketEndPoint(path));
socket.Listen(5);
Console.WriteLine("Server started waiting for client to connect...");
var s = socket.Accept();
Console.WriteLine("Client connected");
var buffer = new byte[1024];
var numberOfBytesReceived = s.Receive(buffer, 0, buffer.Length, SocketFlags.None);
var message = System.Text.Encoding.UTF8.GetString(buffer, 0, numberOfBytesReceived);
Console.WriteLine($"Received: {message}");
}
}
}