利用Tcp和socket实现的客户端与服务端的简单通信
/*服务端*/
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#网络编程的人有所帮助吧,小弟水平很菜,有不对的地方还请论坛里的大侠给小弟指正!