数据字节流处理类
using System;
using System.IO;
using System.Text;
namespace ConsoleSocket
{
class ByteBuffer
{
MemoryStream stream = null;
BinaryWriter writer = null;
BinaryReader reader = null;
public ByteBuffer()
{
stream = new MemoryStream();
writer = new BinaryWriter(stream);
}
public ByteBuffer(byte[] data)
{
if (data != null)
{
stream = new MemoryStream(data);
reader = new BinaryReader(stream);
}
else
{
stream = new MemoryStream();
writer = new BinaryWriter(stream);
}
}
public void Close()
{
if (writer != null) writer.Close();
if (reader != null) reader.Close();
stream.Close();
writer = null;
reader = null;
stream = null;
}
public void WriteByte(byte v)
{
writer.Write(v);
}
public void WriteInt(int v)
{
writer.Write((int)v);
}
public void WriteShort(ushort v)
{
writer.Write((ushort)v);
}
public void WriteLong(long v)
{
writer.Write((long)v);
}
public void WriteFloat(float v)
{
byte[] temp = BitConverter.GetBytes(v);
Array.Reverse(temp);
writer.Write(BitConverter.ToSingle(temp, 0));
}
public void WriteDouble(double v)
{
byte[] temp = BitConverter.GetBytes(v);
Array.Reverse(temp);
writer.Write(BitConverter.ToDouble(temp, 0));
}
public void WriteString(string v)
{
byte[] bytes = Encoding.UTF8.GetBytes(v);
writer.Write((ushort)bytes.Length);
writer.Write(bytes);
}
public void WriteBytes(byte[] v)
{
writer.Write((int)v.Length);
writer.Write(v);
}
public byte ReadByte()
{
return reader.ReadByte();
}
public int ReadInt()
{
return (int)reader.ReadInt32();
}
public ushort ReadShort()
{
return (ushort)reader.ReadInt16();
}
public long ReadLong()
{
return (long)reader.ReadInt64();
}
public float ReadFloat()
{
byte[] temp = BitConverter.GetBytes(reader.ReadSingle());
Array.Reverse(temp);
return BitConverter.ToSingle(temp, 0);
}
public double ReadDouble()
{
byte[] temp = BitConverter.GetBytes(reader.ReadDouble());
Array.Reverse(temp);
return BitConverter.ToDouble(temp, 0);
}
public string ReadString()
{
ushort len = ReadShort();
byte[] buffer = new byte[len];
buffer = reader.ReadBytes(len);
return Encoding.UTF8.GetString(buffer);
}
public byte[] ReadBytes()
{
int len = ReadInt();
return reader.ReadBytes(len);
}
public byte[] ToBytes()
{
writer.Flush();
return stream.ToArray();
}
public void Flush()
{
writer.Flush();
}
}
}
客户端连接服务器
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleSocket
{
public class clientSocket
{
private static byte[] result = new byte[1024];
private static Socket clientSockets;
//是否已连接的标识
public bool IsConnected = false;
public clientSocket()
{
clientSockets = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
}
/// <summary>
/// 连接指定IP和端口的服务器
/// </summary>
/// <param name="ip"></param>
/// <param name="port"></param>
public void ConnectServer(string ip, int port)
{
IPAddress mIp = IPAddress.Parse(ip);
IPEndPoint ip_end_point = new IPEndPoint(mIp, port);
try
{
clientSockets.Connect(ip_end_point);
IsConnected = true;
Console.WriteLine("连接服务器成功");
}
catch
{
IsConnected = false;
Console.WriteLine("连接服务器失败");
}
//服务器下发数据长度
int receiveLength = clientSockets.Receive(result);
ByteBuffer buffer = new ByteBuffer(result);
int len = buffer.ReadShort();
string data = buffer.ReadString();
Console.WriteLine("服务器返回数据:" + data);
}
/// <summary>
/// 发送数据给服务器
/// </summary>
public void SendMessage(string data)
{
if (IsConnected == false)
return;
try
{
ByteBuffer buffer = new ByteBuffer();
buffer.WriteString(data);
clientSockets.Send(WriteMessage(buffer.ToBytes()));
}
catch
{
IsConnected = false;
clientSockets.Shutdown(SocketShutdown.Both);
clientSockets.Close();
}
}
/// <summary>
/// 数据转换,网络发送需要两部分数据,一是数据长度,二是主体数据
/// </summary>
/// <param name="message"></param>
/// <returns></returns>
private static byte[] WriteMessage(byte[] message)
{
MemoryStream ms = null;
using (ms = new MemoryStream())
{
ms.Position = 0;
BinaryWriter writer = new BinaryWriter(ms);
ushort msglen = (ushort)message.Length;
writer.Write(msglen);
writer.Write(message);
writer.Flush();
return ms.ToArray();
}
}
}
}
服务器处理客户端连接
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleSocket
{
class Program
{
private static byte[] result = new byte[1024];
private const int port = 8088;
private static string IpStr = "192.168.3.5";
private static Socket serverSocket;
static void Main(string[] args)
{
IPAddress ip = IPAddress.Parse(IpStr);
IPEndPoint ip_end_point = new IPEndPoint(ip, port);
//创建服务器Socket对象,并设置相关属性
serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//绑定ip和端口
serverSocket.Bind(ip_end_point);
//设置最长的连接请求队列长度
serverSocket.Listen(10);
Console.WriteLine("启动监听{0}成功", serverSocket.LocalEndPoint.ToString());
//在新线程中监听客户端的连接
Thread thread = new Thread(ClientConnectListen);
thread.Start();
Console.ReadLine();
//Socket连接测试
SocketTest();
}
/// <summary>
/// 客户端连接请求监听
/// </summary>
private static void ClientConnectListen()
{
while (true)
{
//为新的客户端连接创建一个Socket对象
Socket clientSocket = serverSocket.Accept();
Console.WriteLine("客户端{0}成功连接", clientSocket.RemoteEndPoint.ToString());
//向连接的客户端发送连接成功的数据
ByteBuffer buffer = new ByteBuffer();
buffer.WriteString("Connected Server");
clientSocket.Send(WriteMessage(buffer.ToBytes()));
//每个客户端连接创建一个线程来接受该客户端发送的消息
System.Threading.Thread thread = new Thread(RecieveMessage);
thread.Start(clientSocket);
}
}
/// <summary>
/// 数据转换,网络发送需要两部分数据,一是数据长度,二是主体数据
/// </summary>
/// <param name="message"></param>
/// <returns></returns>
private static byte[] WriteMessage(byte[] message)
{
MemoryStream ms = null;
using (ms = new MemoryStream())
{
ms.Position = 0;
BinaryWriter writer = new BinaryWriter(ms);
ushort msglen = (ushort)message.Length;
writer.Write(msglen);
writer.Write(message);
writer.Flush();
return ms.ToArray();
}
}
/// <summary>
/// 接收指定客户端Socket的消息
/// </summary>
/// <param name="clientSocket"></param>
private static void RecieveMessage(object clientSocket)
{
Socket mClientSocket = (Socket)clientSocket;
while (true)
{
try
{
int receiveNumber = mClientSocket.Receive(result);
Console.WriteLine("接收客户端{0}消息, 长度为{1}", mClientSocket.RemoteEndPoint.ToString(), receiveNumber);
ByteBuffer buff = new ByteBuffer(result);
//数据长度
int len = buff.ReadShort();
//数据内容
string data = buff.ReadString();
Console.WriteLine("数据内容:{0}", data);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
mClientSocket.Shutdown(SocketShutdown.Both);
mClientSocket.Close();
break;
}
}
}
/// <summary>
/// Socket连接测试
/// </summary>
public static void SocketTest()
{
clientSocket mSocket = new clientSocket();
mSocket.ConnectServer("192.168.3.5", 8088);
mSocket.SendMessage("我是客户端!");
}
}
}