C#提供了方便强大的各种网络编程类,直接上代码了。
A,TCP通信服务器端
class Program
{
public static int port = 1987;
public static string host = "127.0.0.1";
static void Main(string[] args)
{
try
{
IPAddress ip = IPAddress.Parse(host);
IPEndPoint ipe = new IPEndPoint(ip, port);
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
s.Bind(ipe);
s.Listen(5);
Console.WriteLine("start server");
Socket t = s.Accept();
byte[] data = new byte[1024];
int len;
len = t.Receive(data);
string str = Encoding.ASCII.GetString(data, 0, len);
Console.WriteLine("Get: " + str);
str = "data received";
data = Encoding.ASCII.GetBytes(str);
t.Send(data);
t.Close();
Console.WriteLine("stop server");
}
catch (Exception err) {
Console.WriteLine(err.ToString());
}
}
}
TCP通信客户端
class Program
{
static string host = "127.0.0.1";
static int port = 1987;
static void Main(string[] args)
{
try
{
IPAddress ip = IPAddress.Parse(host);
IPEndPoint ipe = new IPEndPoint(ip, port);
TcpClient tc = new TcpClient();
tc.Connect(ipe);
if (tc.Connected)
{
string str = "this is udp connection";
byte[] data = Encoding.ASCII.GetBytes(str);
NetworkStream stream = tc.GetStream();
stream.Write(data, 0, data.Length);
int len = stream.Read(data, 0, data.Length);
str = Encoding.ASCII.GetString(data, 0, data.Length);
Console.WriteLine("Get " + str);
tc.Close();
}
}
catch (Exception err) {
Console.WriteLine(err.ToString());
}
}
}
B,UDP通信服务器端
class Program
{
public static int port = 1987;
static void Main(string[] args)
{
try
{
IPEndPoint ipe = new IPEndPoint(IPAddress.Any, port);
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
s.Bind(ipe);
Console.WriteLine("start server");
byte[] data = new byte[1024];
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
EndPoint remote = (EndPoint)sender;
int len = s.ReceiveFrom(data, ref remote);
string str = Encoding.ASCII.GetString(data, 0, len);
Console.WriteLine("Get: " + str);
str = "data received";
data = Encoding.ASCII.GetBytes(str);
s.SendTo(data, remote);
s.Close();
Console.WriteLine("stop server");
}
catch (Exception err) {
Console.WriteLine(err.ToString());
}
}
}
UDP通信客户端
class Program
{
static string host = "127.0.0.1";
static int port = 1987;
static void Main(string[] args)
{
try
{
IPAddress ip = IPAddress.Parse(host);
IPEndPoint ipe = new IPEndPoint(ip, port);
IPEndPoint ipe_rec = new IPEndPoint(IPAddress.Any, 10080);
UdpClient uc = new UdpClient(10080);
uc.Connect(ipe);
string str = "this is udp connection";
byte[] data = Encoding.ASCII.GetBytes(str);
uc.Send(data, data.Length);
data = uc.Receive(ref ipe);
str = Encoding.ASCII.GetString(data, 0, data.Length);
Console.WriteLine("Get " + str);
}
catch (Exception err) {
Console.WriteLine(err.ToString());
}
}
}