一 .面向连接的套接字编程
1.服务器端
static void Main(string[] args)
{
Socket ns;
Socket ss = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //建立服务器端流式套接字
IPAddress adr = IPAddress.Parse("127.0.0.1");
IPEndPoint ep = new IPEndPoint(adr, 3000); //设置IP地址 端口号
ss.Bind(ep); //用Bind方法把套接字与本地地址绑定,对于服务器程序,套接字必须绑定到本地IP地址和端口上
ss.Listen(3); //开始监听,3指的是队列长度,先入先出,系统等待用户程序排队的连接数,长度直接控制了客户机的并发连接数。
while (true)
{
if ((ns = ss.Accept()) != null) //ss接受客户端的连接请求,连接建立,返回得到新的套接字ns
{
Console.WriteLine("连接上...发送数据....");
byte[] message = { 60, 50, 40, 30, 20, 10, 0 }; //欲发送的字节数组,以0为结束标记
Console.WriteLine("总计将发送" + ns.Send(message) + "个字节的数据"); //send方法返回发送的字节数
Console.WriteLine("结束.");
ns.Close();
break;
}
}
}
2.客户端
static void Main(string[] args)
{
Socket cs = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //建立客户端套接字
IPAddress adr = IPAddress.Parse("127.0.0.1");
IPEndPoint ep = new IPEndPoint(adr, 3000);
cs.Connect(ep); //完成绑定
byte[] buffer = new byte[255];
string data = null;
int recv = 0;
recv = cs.Receive(buffer); //在CS上读/写数据
if (recv > 0)
{
Console.WriteLine("连接上...");
Console.WriteLine("从服务器接收数据...");
data = Encoding.ASCII.GetString(buffer, 0, recv);
Console.WriteLine(data);
while (true)
{
String input;
input = Console.ReadLine();
if (input == "exit")
{
break;
}
cs.Send(Encoding.ASCII.GetBytes(input));
}
Console.WriteLine("连接断开...");
cs.Shutdown(SocketShutdown.Both);
cs.Close();
}
}
二.面向无连接的套接字编程
static void Main(string[] args)
{
Socket cs = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //建立客户端套接字
IPAddress adr = IPAddress.Parse("127.0.0.1");
IPEndPoint ep = new IPEndPoint(adr, 3000);
cs.Connect(ep); //完成绑定
byte[] buffer = new byte[255];
string data = null;
int recv = 0;
recv = cs.Receive(buffer); //在CS上读/写数据
if (recv > 0)
{
Console.WriteLine("连接上...");
Console.WriteLine("从服务器接收数据...");
data = Encoding.ASCII.GetString(buffer, 0, recv);
Console.WriteLine(data);
while (true)
{
String input;
input = Console.ReadLine();
if (input == "exit")
{
break;
}
cs.Send(Encoding.ASCII.GetBytes(input));
}
Console.WriteLine("连接断开...");
cs.Shutdown(SocketShutdown.Both);
cs.Close();
}
}
套接字编程示例
最新推荐文章于 2020-07-18 19:54:29 发布