110,011
社区成员




using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Net.Sockets;
using System.Threading;
using System.Net;
using System.Windows.Forms;
namespace serverchat
{
public class Receiver
{
Socket _socket = null;
NetworkStream _stream = null;
int _index;
Thread _thread = null;
bool _isFree = true;
#region 属性
public Socket Socket
{
get { return _socket; }
set { _socket = value; }
}
public NetworkStream Stream
{
get { return _stream; }
set { _stream = value; }
}
public int Index
{
get { return _index; }
set { _index = value; }
}
public Thread Thread
{
get { return _thread; }
set { _thread = value; }
}
public bool IsFree
{
get { return _isFree; }
set { _isFree = value; }
}
#endregion
//构造方法
public Receiver()
{
this.Thread = new Thread(new ThreadStart(readData));
this.Thread.Start();
}
//激活此线程
public void active(Socket socket, int index)
{
this.IsFree = false;
this.Socket = socket;
this.Index = index;
this.Stream = new NetworkStream(this.Socket);
this.Thread.Resume();
}
//读取数据
public void readData()
{
lock (this)
{
byte[] by=new byte[1024];
int acture = 0;
string content = null;
while (true)
{
try
{
if (this.IsFree)
{
this.Thread.Suspend();
}
else
{
acture = this.Stream.Read(by, 0, by.Length);
content += Encoding.UTF8.GetString(by, 0, acture);
if (!this.Stream.DataAvailable)
{
Pool.sendText(System.Text.Encoding.UTF8.GetBytes(content));
Pool.appendText(content);
content = null;
}
}
}
catch (Exception e)
{
MessageBox.Show(e.Message);
this.IsFree = true;
this.Stream = null;
this.Socket = null;
throw;
}
}
}
}
}
}