我想编一个非常简单的及时聊天的功能,一个客户端(TcpClient)和一个服务器端(TcpListenner),客户端和服务器端都只有一个窗体,都有个一个TEXTBOX和一个发送BUTTON,在TEXTBOX中输入聊天的内容,点击发送,对方就能看的到你发送的内容,文字写入和读取都是用NetWorkStream,现在遇到的一个疑问是?
我点击“发送”,对方怎么知道我发送了信息,并读取我的信息,就像QQ啊,这个是怎么控制的?
我点击“发送”,对方怎么知道我发送了信息,并读取我的信息,就像QQ啊,这个是怎么控制的?
客户端->服务器端->客户端
你在服务器上要保存所有连接上来的SOCKET客户端,这样就可以向他们发信息了。
/// 构造函数
/// </summary>
/// <param name="ip">IP</param>
/// <param name="port">端口</param>
public SocketReceive(string ip, int port)
{
this.serverIP = ip;
this.serverPort = port;
} #region 异步接收Socket
/// <summary>
/// 异步连接服务器
/// </summary>
private void Connent()
{
try
{
if (socket != null && socket.Connected)
{
socket.Shutdown(SocketShutdown.Both);
Thread.Sleep(10);
socket.Close();
}
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ipLocal = new IPEndPoint(IPAddress.Parse(serverIP), serverPort );
socket.Blocking = false;
socket.BeginConnect(ipLocal, new AsyncCallback(Connected), socket);
}
catch (Exception ex)
{
this.Close();
log.Info(ex.Message);
} } private void Connected(IAsyncResult ar)
{
try
{
Socket sock = (Socket)ar.AsyncState;
if (sock.Connected)
{
log.Info("连接成功");
this.Receive();
}
else
{
log.Info("连接失败");
}
}
catch (Exception ex)
{
this.Close();
log.Info(ex.Message);
}
} /// <summary>
/// 异步接收数据
/// </summary>
public void Receive()
{
try
{
if (this.socket == null || !this.socket.Connected)
{
throw new Exception("远程服务器没有连接,请先连接");
}
else
{
socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(OnReceiveData), socket);
}
}
catch (Exception ex)
{
this.Close();
log.Info(ex.Message);
}
} private void OnReceiveData(IAsyncResult ar)
{
Socket sock = (Socket)ar.AsyncState;
try
{
int nBytesRec = sock.EndReceive(ar);
if (nBytesRec > 0)
{
//接受数据并保存
//string sRecieved = Encoding.ASCII.GetString(buffer, 0, nBytesRec);
//log.Info(sRecieved); byte[] retByte = new byte[nBytesRec];
Array.Copy(buffer, retByte, nBytesRec);
if (ReadDataEvt != null)
{
log.Info("ReadDataEvt");
ReadDataEvt(this, retByte);
}
Receive();
}
else
{
sock.Shutdown(SocketShutdown.Both);
sock.Close();
if (receiveData.Length != 0)
{
log.Info("接受数据成功");
}
else
{
log.Info("接受数据为空");
}
}
}
catch (Exception ex)
{
this.Close();
log.Info(ex.Message);
} } private void InitailTimer()
{
this.CheckConnectTimer = new System.Timers.Timer();
this.CheckConnectTimer.Interval = 1000 * 60 * 5;
this.CheckConnectTimer.Elapsed += new System.Timers.ElapsedEventHandler(CheckConnectTimer_Elapsed);
this.CheckConnectTimer.Start();
} void CheckConnectTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
if (this.socket != null)
{
log.Info("CheckConnectTimer_Elapsed socket connect:" + this.socket.Connected);
}
if (this.socket == null || !this.socket.Connected )
{
this.Connent();
}
}
#endregion #region 关闭socket
public void Close()
{
try
{
if (socket != null && socket.Connected)
{
socket.Shutdown(SocketShutdown.Both);
Thread.Sleep(10);
socket.Close();
}
}
catch (Exception ex)
{
log.Info(ex.Message);
}
}
#endregion