///
///Socket建立TCP链接
////
namespace Socket_TCP_服务端
{class Program
{
static void Main(string[] args)
{
//绑定IP和端口给当前程序
Socket TCPServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress ipaddress = new IPAddress(new byte[] { 10, 246, 40, 205 });
EndPoint point = new IPEndPoint(ipaddress, 7788);
TCPServer.Bind(point);
//开始监听
TCPServer.Listen(100);
Socket ClientSocket = TCPServer.Accept();//挂起不往下走 监听 知道有C来连接成功
//Socket通信
//向客户端发送消息
string message = "Hello 世界";
byte[] mesData = Encoding.UTF8.GetBytes(message);
ClientSocket.Send(mesData);
//接收客户端消息
byte[] receivedata = new byte[2048];
int receiveLeng = ClientSocket.Receive(receivedata);
string receivemessge = Encoding.UTF8.GetString(receivedata,0,receiveLeng);
Console.WriteLine("从客户端接收到消息:" + receivemessge);
Console.ReadKey();
}
}
}
namespace Socket_TCP_客户端_001
{
class Program
{
static void Main(string[] args)
{
Socket tcpClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress ipaddress = IPAddress.Parse("10.246.40.205");
EndPoint point = new IPEndPoint(ipaddress, 7788);
//建立连接
tcpClient.Connect(point);
//从服务器接收消息
byte[] data = new byte[1024];
int receiveLength = tcpClient.Receive(data);//接收data 返回值为接收到的长度
string message = Encoding.UTF8.GetString(data, 0, receiveLength);
Console.WriteLine(message);
//向服务端发送消息
string messageClient = Console.ReadLine();
tcpClient.Send(Encoding.UTF8.GetBytes(messageClient));
Console.ReadKey();
}
}
}
///标准接口
- /// <summary>
- /// 连接使用tcp协议的服务端
- /// </summary>
- /// <param name="ip">服务端的ip</param>
- /// <param name="port">服务端的端口号</param>
- /// <returns></returns>
- public static Socket ConnectServer(string ip, int port)
- {
- Socket s = null;
- try
- {
- IPAddress ipAddress = IPAddress.Parse(ip);
- IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, port);
- s = new Socket(ipEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
- s.Connect(ipEndPoint);
- if (s.Connected == false) s = null;
- }
- catch (Exception)
- {
- }
- return s;
- }
- /// <summary>
- /// 连接使用tcp协议的服务端
- /// </summary>
- /// <param name="ip">服务端的ip</param>
- /// <param name="port">服务端的端口号</param>
- /// <returns></returns>
- public static Socket ConnectServer(string ip, int port)
- {
- Socket s = null;
- try
- {
- IPAddress ipAddress = IPAddress.Parse(ip);
- IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, port);
- s = new Socket(ipEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
- s.Connect(ipEndPoint);
- if (s.Connected == false) s = null;
- }
- catch (Exception)
- {
- }
- return s;
- }
-
- /// <summary>
- /// 向远程主机发送数据
- /// </summary>
- /// <param name="socket">连接到远程主机的socket</param>
- /// <param name="buffer">待发送的字符串</param>
- /// <param name="outTime">发送数据的超时时间,单位是秒(为-1时,将一直等待直到有数据需要发送)</param>
- /// <returns>0:发送数据成功;-1:超时;-2:错误;-3:异常</returns>
- public static int SendData(Socket socket, string buffer, int outTime)
- {
- if (buffer == null || buffer.Length == 0)
- {
- throw new ArgumentException("buffer为null或则长度为0.");
- }
- return SendData(socket, System.Text.Encoding.Default.GetBytes(buffer), outTime);
- }
-
- /// <summary>
- /// 接收远程主机发送的数据
- /// </summary>
- /// <param name="socket">要接收数据且已经连接到远程主机的</param>
- /// <param name="buffer">接收数据的缓冲区(需要接收的数据的长度,由 buffer 的长度决定)</param>
- /// <param name="outTime">接收数据的超时时间,单位秒(指定为-1时,将一直等待直到有数据需要接收)</param>
- /// <returns></returns>
- public static int RecvData(Socket socket, byte[] buffer, int outTime)
- {
- if (socket == null || socket.Connected == false)
- {
- throw new ArgumentException("socket为null,或者未连接到远程计算机");
- }
- if (buffer == null || buffer.Length == 0)
- {
- throw new ArgumentException("buffer为null ,或者长度为 0");
- }
- buffer.Initialize();
- int left = buffer.Length;
- int curRcv = 0;
- int hasRecv=0;
- int flag = 0;
- try
- {
- while (true)
- {
- if (socket.Poll(outTime * 1000, SelectMode.SelectRead) == true)
- {
- // 已经有数据等待接收
- curRcv = socket.Receive(buffer, hasRecv, left, SocketFlags.None);
- left -= curRcv;
- hasRecv += curRcv;
- // 数据已经全部接收
- if (left == 0)
- {
- flag = 0;
- break;
- }
- else
- {
- // 数据已经部分接收
- if (curRcv > 0)
- {
- continue;
- }
- else // 出现错误
- {
- flag = -2;
- break;
- }
- }
- }
- else // 超时退出
- {
- flag = -1;
- break;
- }
- }
- }
- catch (SocketException)
- {
- //Log
- flag = -3;
- }
- return flag;
- }
///
///
///Socket建立UDP链接
namespace Socket_UDP_Server
{
class Program
{
public static Socket udpServer;
static void Main(string[] args)
{
//创建UDP 绑定IP端口
udpServer = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
udpServer.Bind(new IPEndPoint(IPAddress.Parse("10.246.40.205"), 8899));
//开启线程
new Thread(ReceiveMessage) { IsBackground = true }.Start();
Console.ReadKey();
}
/// <summary>
/// 接收数据
/// </summary>
static void ReceiveMessage()
{
while (true)
{
EndPoint remoteEP = new IPEndPoint(IPAddress.Any, 0);
byte[] data = new byte[1024];
int length = udpServer.ReceiveFrom(data, ref remoteEP);
string message = Encoding.UTF8.GetString(data, 0, length);
Console.WriteLine("从IP:" + (remoteEP as IPEndPoint).Address + ":" + (remoteEP as IPEndPoint).Port + "收到数据:" + message);
}
}
}
}
namespace Socket_UDP_Client
{
class Program
{
static void Main(string[] args)
{
//创建UDP
Socket udpClient = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
while (true)
{
//发送数据
EndPoint serverPoint = new IPEndPoint(IPAddress.Parse("10.246.40.205"), 8899);
string message = Console.ReadLine();
byte[] data = Encoding.UTF8.GetBytes(message);
udpClient.SendTo(data, serverPoint);
Console.ReadKey();
}
}
}
}