网络通讯(服务端,客户端)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;
using System.Net;
namespace 网络通讯_服务端
{
class Program
{
static void Main(string[] args)
{
//第一步:创建Socket
Socket sk = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//第二步:绑定IP
IPAddress ip = new IPAddress(new byte[] { 192, 168, 1, 3 });//IP地址封装方法
EndPoint ep = new IPEndPoint(ip, 7788);
sk.Bind(ep);//绑定命令
//第三步:开始监听
sk.Listen(100);//设置最大连接数。
Socket Client = sk.Accept();//向连上的客户端发送一条消息
string SendStr = "中华人民共和国万岁,世界人民大团结万岁";
byte[] sendByte = Encoding.UTF8.GetBytes(SendStr);//字符串转Byte类型
Client.Send(sendByte);//发送到客户端。
//以下是服务端等待客户端的消息:
Console.WriteLine("等接收客户端发来的消息:");
byte[] recByte = new byte[1024];
int lenght = Client.Receive(recByte);
string RecStr = Encoding.UTF8.GetString(recByte, 0, lenght);
Console.WriteLine(RecStr);
Console.ReadKey();
}
}
}
==========================下面客户端代码======================================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;
using System.Net;
namespace 网络通讯_客户端
{
class Program
{
static void Main(string[] args)
{
//创建socket
Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//创建connect连接
IPAddress ip = IPAddress.Parse("192.168.1.3");//ip类型转换
EndPoint ePiont = new IPEndPoint(ip, 7788);//连接的端口和IP
clientSocket.Connect(ePiont);//创建连接
byte[] rec = new byte[1024];//接收数据的缓冲区
int ByteLen = clientSocket.Receive(rec);//接收数据,并返回接收数据的长度
string receiveString = Encoding.UTF8.GetString(rec, 0, ByteLen);//接收到的byte类型数据转换string类型
Console.WriteLine(receiveString);//打印输出
//以下是向服务器发送一条消息。
Console.WriteLine("向服务端回复一条消息:");
string ClientSend = Console.ReadLine();
byte[] SendByte = Encoding.UTF8.GetBytes(ClientSend);
clientSocket.Send(SendByte);
Console.ReadKey();
}
}
}
运行结果: