整理说明
1、学习c#时写的示例程序,没有什么价值。
2、使用的UDP协议。
示例代码
using
System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace talk
{
class Program
{
static string toanyone;
static void Main( string [] args)
{
Thread th = new Thread( new ThreadStart(ServerStart));
th.Start();
Console.WriteLine( " ----------欢迎使用聊天程序--------- " );
Console.WriteLine( " 请输入对方ip: " );
toanyone = Console.ReadLine();
do
{
Console.WriteLine( " 请输入您想说的话: " );
string msg = Console.ReadLine();
if (msg.Trim().ToLower() == " exit " )
{
Console.WriteLine( " 退出聊天程序,欢迎再次使用! " );
break ;
}
else
{
SendMessage(msg);
}
}
while ( true );
}
static void SendMessage( string message)
{
UdpClient udpclient = new UdpClient(toanyone, 8090 );
byte [] bytes = Encoding.UTF8.GetBytes(message);
udpclient.Send(bytes, bytes.Length);
Console.WriteLine( " 您说: " + message + " " + DateTime.Now.ToString());
Console.WriteLine( " ------------------------------- " );
}
static void ServerStart()
{
Console.WriteLine( " -----------开始监听------------ " );
UdpClient udplistener = new UdpClient( 8090 );
IPEndPoint guest = new IPEndPoint(IPAddress.Any, 8090 );
while ( true )
{
string Recevied = "" ;
byte [] bytes = udplistener.Receive( ref guest);
Recevied = " 信息来自: " + guest.Address.ToString() + " 说: " + Encoding.UTF8.GetString(bytes);
Console.WriteLine(Recevied);
}
}
}
}
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace talk
{
class Program
{
static string toanyone;
static void Main( string [] args)
{
Thread th = new Thread( new ThreadStart(ServerStart));
th.Start();
Console.WriteLine( " ----------欢迎使用聊天程序--------- " );
Console.WriteLine( " 请输入对方ip: " );
toanyone = Console.ReadLine();
do
{
Console.WriteLine( " 请输入您想说的话: " );
string msg = Console.ReadLine();
if (msg.Trim().ToLower() == " exit " )
{
Console.WriteLine( " 退出聊天程序,欢迎再次使用! " );
break ;
}
else
{
SendMessage(msg);
}
}
while ( true );
}
static void SendMessage( string message)
{
UdpClient udpclient = new UdpClient(toanyone, 8090 );
byte [] bytes = Encoding.UTF8.GetBytes(message);
udpclient.Send(bytes, bytes.Length);
Console.WriteLine( " 您说: " + message + " " + DateTime.Now.ToString());
Console.WriteLine( " ------------------------------- " );
}
static void ServerStart()
{
Console.WriteLine( " -----------开始监听------------ " );
UdpClient udplistener = new UdpClient( 8090 );
IPEndPoint guest = new IPEndPoint(IPAddress.Any, 8090 );
while ( true )
{
string Recevied = "" ;
byte [] bytes = udplistener.Receive( ref guest);
Recevied = " 信息来自: " + guest.Address.ToString() + " 说: " + Encoding.UTF8.GetString(bytes);
Console.WriteLine(Recevied);
}
}
}
}