/*服務端*/
using System;
using System.Collections.Generic;
using System.Collections;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Threading;
namespace ChatSever
{ class Sever
{
static void Main(string[] args)
{
Hashtable clientTable = new Hashtable();//存放連接的轉發表
IPAddress ip = Dns.GetHostAddresses(Dns.GetHostName())[0];//返回主機的ip地址
int port=9999;
int maxsize=1024;
TcpListener listener = new TcpListener(ip, port);
listener.Start();
Console.WriteLine("服務器已啓動,正在監聽....../n");
Console.WriteLine(string.Format("服務器IP:{0}/t端口號:{1}/n",ip,port));
while (true)
{
byte[] packetBuff=new byte[maxsize];
Socket newClient = listener.AcceptSocket();
newClient.Receive(packetBuff);
string userName = Encoding.Unicode.GetString(packetBuff).TrimEnd('/0');
if (clientTable.Count != 0 && clientTable.ContainsKey(userName))//驗證是否爲唯一用戶
{
newClient.Send(Encoding.Unicode.GetBytes("Failed"));
continue;
}
else
{
newClient.Send(Encoding.Unicode.GetBytes("Successful"));
}
//將新的連接加入轉發表並創建線程爲其服務
clientTable.Add(userName,newClient);
string strlog = string.Format("[系統消息]用戶{0}在{1}連接.... 當前在線人數:{2}/r/n/r/n",userName ,DateTime.Now ,clientTable.Count);
Console.WriteLine(strlog);
Thread thread = new Thread(new ParameterizedThreadStart(Sever.ThreadFunc));
thread.Start(userName);
//向所有客戶端發送系統消息
foreach (DictionaryEntry de in clientTable)
{
string clientName = de.Key as string;
Socket clientSkt = de.Value as Socket;
if (!clientName.Equals(userName))
{
clientSkt.Send(Encoding.Unicode.GetBytes(strlog));
}
}
}
}
static void ThreadFunc(object obj)
{
//代碼----啓動新的線程監聽來自客戶端的信息
}
}
}
/*客戶端:*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace CustomProgram
{
class Custom
{
static void Main(string[] args)
{
byte [] data=new byte[1024];
Socket newClient = new Socket(AddressFamily.InterNetwork ,SocketType.Stream,ProtocolType.Tcp);
Console.WriteLine("請輸入服務器的地址:");
string ipadd = Console.ReadLine();
Console.WriteLine("請輸入服務的端口號:");
int port = Convert.ToInt32(Console.ReadLine());
IPEndPoint ipend = new IPEndPoint(IPAddress .Parse(ipadd) ,port);
try
{
newClient.Connect(ipend);//連接服務器;
}
catch(SocketException e)
{
Console.WriteLine("連接服務器失敗!");
Console.WriteLine(e.Message);
return;
}
int rec = newClient.Receive(data);
string stringdata = Encoding.ASCII.GetString(data,0,rec);
Console.WriteLine(stringdata);
while (true)
{
string input = Console.ReadLine();
if (input.ToUpper() == "EXIT")
break;
newClient.Send(Encoding.ASCII .GetBytes(input));
data =new byte[1024];
rec = newClient.Receive(data);
stringdata = Encoding.ASCII.GetString(data,0,rec);
Console.WriteLine("{0}來自服務器消息:{1}",DateTime.Now,stringdata);
}
Console.WriteLine("斷開連接!");
newClient.Shutdown(SocketShutdown.Both);
newClient.Close();
}
}
}
一上完成之後,右擊項目解決方案的屬性把項目設爲多啓動,同時運行客戶端與服務端即可;
希望這個實例能對剛學C#網絡編程的人有所幫助吧,小弟水平很菜,有不對的地方還請論壇裏的大俠給小弟指正!