노출되는 이미지가 불편하시겠지만 양해를 구합니다. 노출, 클릭등에 관한 자료로 활용 중입니다.
C# Packet Class
바이트 버퍼링 전송 수신 send receive
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.IO;
namespace LClient
{
public partial class Packet
{
NetworkStream _stream;
BinaryWriter _writer;
byte[] _buffer;
byte[] _data;
public void setStream( NetworkStream stream )
{
_stream = stream;
_writer = new BinaryWriter(_stream);
}
public void read()
{
byte[] blen = new byte[4];
int read = _stream.Read(blen, 0, blen.Length);
int ilen = BitConverter.ToInt32(blen,0);
_data = new byte[ilen];
_stream.Read(_data, 0, ilen);
}
public int readInt()
{
//보관
byte[] t = new byte[_data.Length];
Array.Copy(_data, 0, t, 0, _data.Length);
byte[] idata = new byte[4];
Array.Copy(_data, 0, idata, 0, idata.Length);
_data = new byte[t.Length - idata.Length];
Array.Copy(t, idata.Length, _data, 0, _data.Length);
return BitConverter.ToInt32(idata, 0);
}
public String readUTF8()
{
//보관
byte[] t = new byte[_data.Length];
Array.Copy(_data, 0, t, 0, _data.Length);
byte[] sl = new byte[2];
Array.Copy(_data, 0, sl, 0, sl.Length );
short slen = BitConverter.ToInt16(sl,0);
byte[] sd = new byte[slen];
Array.Copy(_data, 0, sd, 0, sd.Length);
if ( t.Length < sl.Length+slen )
{
return null;
}
else
{
_data = new byte[t.Length - (sl.Length + sd.Length)];
Array.Copy(t,(sl.Length+sd.Length),
_data,0, _data.Length);
return Encoding.UTF8.GetString(sd);
}
}
public void WriteInt( int num )
{
if (_buffer == null)
{
_buffer = BitConverter.GetBytes(num);
}
else
{
byte[] b = BitConverter.GetBytes(num);
byte[] t = new byte[_buffer.Length];
Array.Copy(_buffer, 0, t, 0, _buffer.Length);
_buffer = new byte[t.Length + b.Length];
Array.Copy(t, 0, _buffer, 0, t.Length);
Array.Copy(b, 0, _buffer, t.Length, b.Length);
}
}
public void WriteUTF( String str )
{
if (_buffer == null)
{
byte[] b = Encoding.UTF8.GetBytes(str);
byte[] a = BitConverter.GetBytes((short)b.Length);
_buffer = new byte[a.Length + b.Length];
Array.Copy(a, 0, _buffer, 0, a.Length);
Array.Copy(b, 0, _buffer, a.Length, b.Length);
}
else
{
byte[] t = new byte[_buffer.Length];
Array.Copy(_buffer, 0, t, 0, _buffer.Length);
byte[] b = Encoding.UTF8.GetBytes(str);
byte[] a = BitConverter.GetBytes((short)b.Length);
_buffer = new byte[t.Length + a.Length + b.Length];
Array.Copy(t, 0, _buffer, 0, t.Length);
Array.Copy(a, 0, _buffer, t.Length, a.Length);
Array.Copy(b, 0, _buffer, t.Length + a.Length, b.Length);
}
}
public void Flush()
{
// size
_writer.Write(_buffer.Length);
// data
_stream.Write(_buffer, 0, _buffer.Length);
_stream.Flush();
}
public int getLength()
{
return _buffer.Length;
}
public byte[] getData()
{
return _data;
}
}
}
'Application, App > VC++' 카테고리의 다른 글
OnTimer - SetTimer (0) | 2016.12.15 |
---|---|
Stack with std::list (0) | 2016.12.15 |
Effective C++ 목차 (0) | 2016.12.15 |
IO Completion Port 작성하기 ( 2010.10.06 ) (0) | 2016.12.15 |