服务端代码:
static void Main(string[] args)
{
Socket socket = null;
Socket client = null;
try
{
Console.WriteLine("输入IP地址:");
string sIP = Console.ReadLine();
Console.WriteLine("输入端口:");
int iPort = Convert.ToInt32(Console.ReadLine());
IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(sIP), iPort);
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Bind(ipep);//绑定
socket.Listen(10);//监听
Console.WriteLine("********************等待客户端连接*************************************");
//当有可用的客户端连接尝试时执行,并返回一个新的socket,用于与客户端之间的通信
client = socket.Accept();
IPEndPoint clientIP = (IPEndPoint)client.RemoteEndPoint;
Console.WriteLine("客户端连接:(IP地址:" + clientIP.Address + " ;端口:" + clientIP.Port + ")");
byte[] data = new byte[1024];
string welcome = "####################Hello World######################";
data = Encoding.Default.GetBytes(welcome);
client.Send(data, data.Length, SocketFlags.None);//发送信息
int iLength = 0;
while (true)//用死循环来不断的从客户端获取信息,并且转发回去
{
data = new byte[1024];
iLength = client.Receive(data);
Console.WriteLine("接收信息长度:" + iLength);
if (iLength == 0)//当信息长度为0,说明客户端连接断开
{
break;
}
Console.WriteLine("接收信息:" + Encoding.Default.GetString(data, 0, iLength));
client.Send(data, iLength, SocketFlags.None);
}
Console.WriteLine("断开客户端连接:" + clientIP.Address);
Console.Read();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.Read();
}
finally
{
client.Close();
socket.Close();
}
}
客户端代码:
static void Main(string[] args)
{
Socket client = null;
try
{
client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Console.WriteLine("输入IP地址:");
string sIP = Console.ReadLine();
Console.WriteLine("输入端口:");
int iPort = Convert.ToInt32(Console.ReadLine());
IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(sIP), iPort);//服务器的IP和端口
try
{
//因为客户端只是用来向特定的服务器发送信息,所以不需要绑定本机的IP和端口、不需要监听、只需要尝试去连接
client.Connect(ipep);
}
catch (SocketException e)
{
Console.WriteLine("-----------------------尝试连接失败-----------------------");
Console.WriteLine(e.ToString());
return;
}
string input = String.Empty;
byte[] data = new byte[1024];
int iLength = 0;
while (true)//死循环向服务端发送信息,并且接收服务端发送来的消息
{
iLength = client.Receive(data);
if (iLength > 0)
{
input = Encoding.Default.GetString(data, 0, iLength);
Console.WriteLine("接收信息长度:" + iLength);
Console.WriteLine("接收信息:" + input);
}
Console.WriteLine("输入发送信息:");
input = Console.ReadLine();
if (input.ToLower() == "exit" || input.ToLower() == "quit")
{
break;
}
client.Send(Encoding.Default.GetBytes(input));
}
Console.WriteLine("-----------------------从服务端断开连接-----------------------");
Console.Read();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.Read();
}
finally
{
client.Shutdown(SocketShutdown.Both);
client.Close();
}
}