using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading;
using System.Diagnostics;
namespace ClientTest
{
public partial class Form1 : Form
{
private TcpClient client; // TCP 네트워크 서비스에 대한 클라이언트 연결 제공
private NetworkStream myStream; // 네트워크 스트림
private StreamReader myRead; // 스트림 읽기
private Thread myReader; //스레드
private int[] data;
int i = 0;
int[] intArr2;
public Form1()
{
InitializeComponent();
data = new int[20];
}
private void Form1_Load(object sender, EventArgs e)
{
client = new TcpClient();
client.Connect("localhost", 2007);
MessageView("Connected to Server");
myStream = client.GetStream();
myRead = new StreamReader(myStream);
myReader = new Thread(Receive);
myReader.Start();
}
private void Receive()
{
byte[] size = new byte[64];
byte[] data2;
while (true)
{
if (myStream.CanRead)
{
myStream.Read(size, 0, size.Length);
intArr2 = new int[BitConverter.ToInt32(size, 0)];
data2 = new byte[intArr2.Length * 4];
myStream.Read(data2, 0, data2.Length);
for (int z = 0; z < intArr2.Length; z++)
{
intArr2[z] = byteToInt(data2, z * 4);
Debug.WriteLine(intArr2[z]);
}
/*
string msg = myRead.ReadLine();
if (msg.Length > 0)
{
MessageView(msg);
}*/
}
}
}
public int byteToInt(byte[] data, int idx)
{
return
(
/*
16진수 0xFF는 255를 나타낸다.
0xFF를 & (AND 연산)하는 이유는
원래 음수가 아니었는데 byte로 자르다보면 부호비트에 1이 들어와서 음수가 되는 경우가 있다.
그 음수값을 다시 복구하기 위해서 0xFF를 2진수(마지막 8비트만 1이고 나머지는 0)로 AND 연산하면 부호비트는 0이 되어 본래 부호 그대로 들어오고 8비트는 그대로 복원될 수 있다.
이것을 다시 쉬프팅하고 OR연산을 하면 이전의 int 값이 나오게 된다.
| (OR연산) 대신 + 를 해도 되지만 비트연산이 더 빠르기 때문에 OR연산을 사용한다.
*/
((data[idx] & 0xFF) << 24) |
((data[++idx] & 0xFF) << 16) |
((data[++idx] & 0xFF) << 8) |
(data[++idx] & 0xFF)
);
}
private void showData()
{
for(int j=0; j <= i; j++)
{
this.txtMessage.AppendText(data[j] + "\r\n");
}
this.txtMessage.Focus();
this.txtMessage.ScrollToCaret();
}
private void MessageView(string strText)
{
this.txtMessage.AppendText(strText + "\r\n");
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
try
{
if (!(myRead == null))
{
myRead.Close();
}
if (!(myStream == null))
{
myStream.Close();
}
if (!(client == null))
{
client.Close();
}
if (!(myReader == null))
{
myReader.Abort();
}
}
catch
{
return;
}
}
}
}