最后,我就综合以上C#网络编程的一些知识,向大家展示一个很好的实例。
///服务端
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Net.Sockets;
using System.Net;
namespace ConsoleApplication1
{
class Program
{
static Thread mythread;//定义线程
static Socket socket;
static int port = 8000;//定义端口
/// <summary>
/// 服务端
/// </summary>
/// <param name="args"></param>
static void Main(string[] args)
{
try
{
mythread = new Thread(new ThreadStart(BeginListener));
mythread.Start();
}
catch (Exception ex)
{
}
}
/// <summary>
/// 获取本地ip地址
/// </summary>
/// <returns></returns>
public static IPAddress GetServerIp()
{
IPHostEntry ip = Dns.GetHostEntry(Dns.GetHostName());
return ip.AddressList[0];
}
/// <summary>
/// 开始监听
/// </summary>
private static void BeginListener()
{
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress ServerIp = GetServerIp();
IPEndPoint ipEndPoint = new IPEndPoint(ServerIp, port);
socket.Bind(ipEndPoint);
Console.WriteLine(ipEndPoint.ToString() + "正在监听!");
byte[] byteMessage = new byte[100];
while (true)
{
try
{
socket.Listen(5);
Socket newSocket = socket.Accept();
newSocket.Receive(byteMessage);
string sTime = DateTime.Now.ToShortTimeString();
string msg = sTime + "-" + ServerIp.ToString() + "信息来自:";
msg += " " + Encoding.Default.GetString(byteMessage).Trim(new char[] { '\0' });
Console.WriteLine(msg.ToString() + "\r\n");
}
catch (SocketException ex)
{
Console.WriteLine(ex.ToString());
}
}
}
}
}
///客户端
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
namespace ConsoleApplication2
{
class Program
{
/// <summary>
/// 客户端
/// </summary>
/// <param name="args"></param>
static void Main(string[] args)
{
SendMessage();
ConsoleKey key;
do
{
Console.WriteLine("输入\"Q\"键退出");
key = Console.ReadKey(true).Key;
}
while (key != ConsoleKey.Q);
}
/// <summary>
/// 获取本机地址
/// </summary>
/// <returns></returns>
public static IPAddress GetClientIp()
{
IPHostEntry ip = Dns.GetHostEntry(Dns.GetHostName());
return ip.AddressList[0];
}
/// <summary>
/// 发送数据
/// </summary>
private static void SendMessage()
{
string sTime=DateTime.Now.ToShortTimeString();
IPAddress ip = GetClientIp();
string port = "8000";
string message = "nice to meet you";
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
int ServerPort = int.Parse(port);
IPEndPoint ipEndPoint = new IPEndPoint(ip, ServerPort);
socket.Connect(ipEndPoint);
byte[] byteMessage;
byteMessage = Encoding.ASCII.GetBytes(message);
socket.Send(byteMessage);
socket.Shutdown(SocketShutdown.Both);
socket.Close();
string msg = sTime + "-" +ip.ToString()+ "发送信息:" + message;
Console.WriteLine(msg);
Console.WriteLine("发送数据成功");
}
}
}