tcp udp均可以用来网络通信,在使用之前建议先搜索一下相关网络连接的基本知识,可以更好的理解和使用,tcp建议看下如下文章:https://blog.csdn.net/chuangsun/article/details/67640242,建议多搜一下多看看。
直接上正文。。。。。。。。。。。。。。。
(1)socket类
采用socket类,使用最基本的同步方法。
tcp服务端
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading; namespace net
{
class Program
{
static void Main(string[] args)
{
string host = "127.0.0.1";
IPAddress ip = IPAddress.Parse(host); //定义侦听端口
//IPEndPoint ipEnd = new IPEndPoint(IPAddress.Any, 8889);
IPEndPoint ipEnd = new IPEndPoint(IPAddress.Any, );
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Bind(ipEnd);
socket.Listen();
Console.Write("Waiting for a client\r\n"); //一旦接受连接,创建一个客户端
Socket client = socket.Accept();
IPEndPoint ipEndClient = (IPEndPoint)client.RemoteEndPoint;
Console.Write("已连接:IP: {0} 端口: {1}\r\n", ipEndClient.Address, ipEndClient.Port); while(true)
{
//接收数据
byte[] recv1 = new byte[];
int count1 = client.Receive(recv1);
string str = Encoding.ASCII.GetString(recv1, , count1);
Console.WriteLine("Client:" + Encoding.ASCII.GetString(recv1, , count1)); if(str=="exit")
{
break;
} //发送数据
string welcome = "Server received:"+ str;
byte[] data = new byte[];
data = Encoding.ASCII.GetBytes(welcome);
client.Send(data, data.Length, SocketFlags.None);
} Thread.Sleep();
Console.Write("\r\n断开连接: {0}", ipEndClient.Address);
client.Close();
socket.Close();
Console.ReadKey();
}
}
}
tcp客户端
using System;
using System.Net;
using System.Net.Sockets;
using System.Collections.Generic;
using System.Text;
using System.Threading; namespace client
{
class Program
{
static void Main(string[] args)
{
//定义主机的IP及端口
IPAddress ip = IPAddress.Parse("127.0.0.1");
IPEndPoint ipEnd = new IPEndPoint(ip, );
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Connect(ipEnd); while(true)
{
//发送数据
string msg = Console.ReadLine();
byte[] msgBytes = new byte[];
msgBytes = Encoding.ASCII.GetBytes(msg);
socket.Send(msgBytes, msgBytes.Length, SocketFlags.None); //接收数据
byte[] recvMsg = new byte[];
int count = socket.Receive(recvMsg);
string recvStr = Encoding.ASCII.GetString(recvMsg, , count);
Console.WriteLine(recvStr); if(msg=="exit")
{
break;
}
} Thread.Sleep();
Console.Write("断开连接");
socket.Shutdown(SocketShutdown.Both);
socket.Close();
Console.ReadKey();
} }
}
udp服务端:
using System;
using System.Text;
using System.Net;
using System.Net.Sockets; namespace UDP
{
class Program
{
static void Main(string[] args)
{
int recv;
byte[] data = new byte[]; IPEndPoint ip = new IPEndPoint(IPAddress.Any, );
Socket Server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
Server.Bind(ip);
Console.WriteLine("Server ready!"); //得到客户机IP
//IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
//EndPoint Remote = (EndPoint)(sender);
//recv = Server.ReceiveFrom(data, ref Remote);
//Console.Write("Message from "+Remote.ToString()+":");
//Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv)); ////客户机连接成功后,发送信息
//string welcome = "Hello ! ";
//data = Encoding.ASCII.GetBytes(welcome);
//Server.SendTo(data, data.Length, SocketFlags.None, Remote); while(true)
{
//得到客户机IP
IPEndPoint sender = new IPEndPoint(IPAddress.Any, );
EndPoint Remote =sender;
recv = Server.ReceiveFrom(data, ref Remote);
string recvStr = Encoding.ASCII.GetString(data, , recv);
Console.Write("Message from " + Remote.ToString() + ":");
Console.WriteLine(recvStr); //客户机连接成功后,发送信息
string welcome = "Server received: "+ recvStr;
data = Encoding.ASCII.GetBytes(welcome);
Server.SendTo(data, data.Length, SocketFlags.None, Remote);
}
//while (true)
//{
// data = new byte[1024];
// //发送接收信息
// recv = Server.ReceiveFrom(data, ref Remote);
// Console.Write("Message from " + Remote.ToString() + ":");
// Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv)); // if (Encoding.ASCII.GetString(data, 0, recv) == "exit")
// break; // Server.SendTo(data, recv, SocketFlags.None, Remote);
//}
//Console.WriteLine("停止");
Server.Close();
Console.ReadKey();
}
}
}
udp客户端:
using System;
using System.Text;
using System.Net;
using System.Net.Sockets; namespace UDPClient
{
class Program
{
static void Main(string[] args)
{
byte[] data = new byte[];
IPEndPoint ip = new IPEndPoint(IPAddress.Parse("192.168.8.15"), );
Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
Console.WriteLine("Client ready:"); //string welcome = "Server hello!";
//data = Encoding.ASCII.GetBytes(welcome);
//server.SendTo(data, data.Length, SocketFlags.None, ip); //IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
//EndPoint Remote = (EndPoint)sender;
//data = new byte[1024];
//int recv = server.ReceiveFrom(data, ref Remote);
//Console.Write("Message from "+Remote.ToString()+":");
//Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv)); while(true)
{
string welcome = Console.ReadLine();
data = Encoding.ASCII.GetBytes(welcome);
server.SendTo(data, data.Length, SocketFlags.None, ip); IPEndPoint sender = new IPEndPoint(IPAddress.Any, );
EndPoint Remote = sender;
data = new byte[];
int recv = server.ReceiveFrom(data, ref Remote);
Console.Write("Message from " + Remote.ToString() + ":");
Console.WriteLine(Encoding.ASCII.GetString(data, , recv));
}
//while (true)
//{
// input = Console.ReadLine();
// server.SendTo(Encoding.ASCII.GetBytes(input), Remote); // if (input == "exit")
// break; // data = new byte[1024];
// recv = server.ReceiveFrom(data, ref Remote);
// stringData = Encoding.ASCII.GetString(data, 0, recv);
// Console.Write("Message from " + Remote.ToString() + ":");
// Console.WriteLine(stringData);
//}
Console.WriteLine("停止");
server.Close();
Console.ReadKey();
}
}
}
(2)TcpClient UdpClient TcpListener类
上述连个类为.NET自封装两个类。
tcp服务端:
using System;
using System.Net;
using System.Net.Sockets;
using System.Text; namespace TcpServerT
{
class Program
{
static void Main(string[] args)
{
//IPAddress IP = IPAddress.Parse("127.0.0.1");
TcpListener listener = new TcpListener(IPAddress.Any, );
listener.Start();
Console.WriteLine("开始监听:"); //此处也可以采用socket 接收,可以方便进行socket操作
//Socket s = listener.AcceptSocket();
TcpClient client = listener.AcceptTcpClient();//接受一个Client
Console.WriteLine("已连接:");
NetworkStream stream = client.GetStream();//获取网络流
Console.WriteLine("获取连接流:");
string receiveString = ""; while (true)
{
byte[] buffer = new byte[client.ReceiveBufferSize];
stream.Read(buffer, , buffer.Length);//读取网络流中的数据
receiveString = Encoding.Default.GetString(buffer).Trim('\0');//转换成字符串
//StreamReader sr = new StreamReader(stream);
//receiveString = sr.ReadToEnd(); string sendMsg = "Server received:" + receiveString;
byte[] sendBytes = Encoding.Default.GetBytes(sendMsg);
stream.Write(sendBytes, , sendBytes.Length);
stream.Flush(); Console.WriteLine(receiveString);
//Console.WriteLine("While++");
if (receiveString == "exit")
{
stream.Close();//关闭流
client.Close();//关闭Client
break;
}
}
listener.Stop();
}
}
}
tcp客户端:
using System;
using System.Net;
using System.Net.Sockets;
using System.Text; namespace TcpClientT
{
class Program
{
static void Main(string[] args)
{
//IPAddress IP = IPAddress.Parse("192.168.8.15");
//IPEndPoint ip = new IPEndPoint(IP, 1234);
//TcpClient client = new TcpClient("192.168.8.15",1234);
IPEndPoint ip = new IPEndPoint(IPAddress.Any, );
TcpClient client = new TcpClient("127.0.0.1", ); NetworkStream sendStream = client.GetStream(); while (true)
{
string msg = Console.ReadLine();
Byte[] sendBytes = Encoding.Default.GetBytes(msg);
sendStream.Write(sendBytes, , sendBytes.Length);
sendStream.Flush();
//StreamWriter sw = new StreamWriter(sendStream);
//sw.WriteLine(msg);
//sw.Flush(); byte[] buffer = new byte[client.ReceiveBufferSize];
sendStream.Read(buffer, , buffer.Length);//读取网络流中的数据
string receiveMsg = Encoding.Default.GetString(buffer).Trim('\0');//转换成字符串 Console.WriteLine(receiveMsg); if (msg == "exit")
{
sendStream.Close();//关闭网络流
break;
}
}
client.Close();//关闭客户端
}
}
}
udp服务端
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text; namespace UdpServer
{
class Program
{
static void Main(string[] args)
{
UdpClient udpServer = new UdpClient(); while (true)
{
var remoteEP = new IPEndPoint(IPAddress.Any, );
byte[] recvData = udpServer.Receive(ref remoteEP); // listen on port 11000
string recvString = Encoding.Default.GetString(recvData);
Console.Write("Source from" + remoteEP.ToString()+":"+ recvString); if(recvString=="exit")
{
break;
} string sendString = "Server received:" + recvString;
byte[] sendData = Encoding.Default.GetBytes(sendString);
udpServer.Send(sendData, sendData.Length, remoteEP); // reply back
}
udpServer.Close();
}
}
}
udp客户端:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text; namespace UdpClientT
{
class Program
{
static void Main(string[] args)
{
UdpClient client = new UdpClient();
IPEndPoint ep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), ); // endpoint where server is listening
client.Connect(ep); while(true)
{
string sendString = Console.ReadLine();
byte[] sendData = Encoding.Default.GetBytes(sendString);
client.Send(sendData, sendData.Length); byte[] recvData = client.Receive(ref ep);
string recvString = Encoding.Default.GetString(recvData);
Console.WriteLine(recvString); if (sendString == "exit") break;
}
client.Close();
}
}
}
PS:最基本的同步方法为阻塞线程模式,即在接受消息或者服务端等待连接过程中,主程序在此位置属于阻塞(卡住)状态,只有这一步执行完毕(收到消息或者建立连接)才会进行下一步。所以可以通过死循环来实现循环接受消息。
udp不存在严格意义上的客户端服务端,只是要确定消息发送的目标主机
如 Socket client = socket.Accept();
int count1 = client.Receive(recv1);