服务器RemoteClient
using System;
using System.Net.Sockets;
using System.Text;
using System.Linq;
namespace Server
{
class RemoteClient
{
private TcpClient client;
private NetworkStream streamToClient;
private const int BufferSize = 8192;
private byte[] buffer;
private int currentId;
public RemoteClient(TcpClient client)
{
this.client = client;
currentId = Program.dictInfo.Where(q => q.Value == client.Client.RemoteEndPoint.ToString()).Select(q => q.Key).ElementAt(0);
Console.WriteLine("\n客户端已连接!{0} <-- {1}",
client.Client.LocalEndPoint, client.Client.RemoteEndPoint);
streamToClient = client.GetStream();
buffer = new byte[BufferSize];
AsyncCallback callBack = new AsyncCallback(ReadComplete);
streamToClient.BeginRead(buffer, 0, BufferSize, callBack, null);
}
private void ReadComplete(IAsyncResult ar)
{
int bytesRead = 0;
try
{
lock (streamToClient)
{
bytesRead = streamToClient.EndRead(ar);
}
if (bytesRead == 0) throw new Exception("读取到0字节");
string msg = Encoding.Unicode.GetString(buffer, 0, bytesRead);
Array.Clear(buffer, 0, buffer.Length);
string[] arrayMsg = msg.Split(new string[] { "$" }, StringSplitOptions.None);
int clientId = int.Parse(arrayMsg[0]);
if (clientId >= 100)
{
try
{
NetworkStream destStream = Program.dict[clientId].GetStream();
byte[] destMsg = Encoding.Unicode.GetBytes("来自" + currentId + "的信息:" + arrayMsg[1]);
destStream.Write(destMsg, 0, destMsg.Length);
destStream.Flush();
Console.WriteLine("收到<{0}>信息转发到<{1}>: {2}", currentId, clientId, arrayMsg[1]);
}
catch (Exception)
{
byte[] destMsg = Encoding.Unicode.GetBytes("<" + clientId + ">下线了,发送失败");
streamToClient.Write(destMsg, 0, destMsg.Length);
streamToClient.Flush();
}
}
else
{
byte[] destMsg = Encoding.Unicode.GetBytes("<" + currentId + ">" + arrayMsg[1]);
streamToClient.Write(destMsg, 0, destMsg.Length);
streamToClient.Flush();
Console.WriteLine("收到<{0}>信息: {1}", currentId, arrayMsg[1]);
}
lock (streamToClient)
{
AsyncCallback callBack = new AsyncCallback(ReadComplete);
streamToClient.BeginRead(buffer, 0, BufferSize, callBack, null);
}
}
catch (Exception ex)
{
if (streamToClient != null)
streamToClient.Dispose();
client.Close();
Console.WriteLine(ex.Message);
}
}
}
}
服务器main
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
namespace Server
{
class Program
{
public static Dictionary<int, TcpClient> dict = new Dictionary<int, TcpClient>();
public static Dictionary<int, string> dictInfo = new Dictionary<int, string>();
static void Main(string[] args)
{
Console.WriteLine("服务器开始运行 ... ");
IPAddress ip = new IPAddress(new byte[] { 127, 0, 0, 1 });
TcpListener listener = new TcpListener(ip, 8500);
listener.Start();
Console.WriteLine("开始侦听 ...");
int clientId = 100;
while (true)
{
TcpClient client = listener.AcceptTcpClient();
dict.Add(clientId, client);
dictInfo.Add(clientId, client.Client.RemoteEndPoint.ToString());
clientId++;
RemoteClient wapper = new RemoteClient(client);
}
}
}
}
客户端ServerClient
using System;
using System.Net.Sockets;
using System.Text;
namespace Client
{
class ServerClient
{
private const int BufferSize = 8192;
private byte[] buffer;
private TcpClient client;
private NetworkStream streamToServer;
private string msg = "";
public ServerClient()
{
try
{
client = new TcpClient();
client.Connect("localhost", 8500);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return;
}
buffer = new byte[BufferSize];
Console.WriteLine("已连接到服务器!{0} --> {1}",
client.Client.LocalEndPoint, client.Client.RemoteEndPoint);
streamToServer = client.GetStream();
}
public void SendMessage(string msg)
{
byte[] temp = Encoding.Unicode.GetBytes(msg);
try
{
streamToServer.Write(temp, 0, temp.Length);
Console.WriteLine("发送信息: {0}", msg);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
lock (streamToServer)
{
AsyncCallback callBack = new AsyncCallback(ReadComplete);
streamToServer.BeginRead(buffer, 0, BufferSize, callBack, null);
}
}
public void SendMessage()
{
SendMessage(this.msg);
}
private void ReadComplete(IAsyncResult ar)
{
int bytesRead;
try
{
lock (streamToServer)
{
bytesRead = streamToServer.EndRead(ar);
}
if (bytesRead == 0) throw new Exception("读取到0字节");
string msg = Encoding.Unicode.GetString(buffer, 0, bytesRead);
Console.WriteLine("收到信息: {0}", msg);
Array.Clear(buffer, 0, buffer.Length);
lock (streamToServer)
{
AsyncCallback callBack = new AsyncCallback(ReadComplete);
streamToServer.BeginRead(buffer, 0, BufferSize, callBack, null);
}
}
catch (Exception ex)
{
if (streamToServer != null)
streamToServer.Dispose();
client.Close();
Console.WriteLine(ex.Message);
}
}
}
}
客户端main
using System;
namespace Client
{
class Program
{
static void Main(string[] args)
{
ServerClient client = new ServerClient();
client.SendMessage("0$初始化连接请求");
while (true)
{
client.SendMessage(Console.ReadLine());
}
}
}
}