小妹求问:TCPClient实时接收字符串问题!
小妹我写了一个Socket程序!
不能实时接收一接收就是所有返回消息都接收一遍!
每发送一条消息,都在把以前的消息接收一遍,我只想接收最后一条消息,然后输出,并且如果我不发送消息,接收消息的那个线程就死掉了。
请问各位师哥如何解决。
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Collections;
namespace TcpClientTest
{
class MCC
{
private StreamReader m_Read = null;
private StreamWriter m_Write = null;
private TcpClient tcp;
private Thread m_ReceiveDataThread = null;
private string m_Username = null;
private string m_Password = null;
public void Login()
{
tcp = new TcpClient();
try
{
tcp.Connect( "192.168.1.10 ",8000);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
this.m_Username = "Test ";
this.m_Password = "123 ";
m_Read = new StreamReader(tcp.GetStream(), Encoding.GetEncoding( "GB2312 "));
m_Write = new StreamWriter(tcp.GetStream(), Encoding.GetEncoding( "GB2312 "));
SendMessageToServer( "i " + m_Username + ", " + m_Password);
}
//发送消息
private void SendMessageToServer(string Message)
{
m_Write.WriteLine(Message);
m_Write.Flush();
}
//接收消息线程
public void Receive()
{
m_ReceiveDataThread = new Thread(new ThreadStart(this.ReceiveDataThread));
m_ReceiveDataThread.Start();
}
//接收消息方法
private void ReceiveDataThread()
{
string line = " ";
try
{
while ((line = m_Read.ReadLine()).Length > = 0)
{
string m = line.Substring(0, 1);
switch (m)
{
case "w ":
Console.WriteLine(line);
break;
case "i ":
Console.WriteLine(line);
break;
default:
break;
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
static void Main(string[] args)
{
TcpClientTest.MCC myEvent = new TcpClientTest.MCC();
myEvent.Login();
myEvent.Receive();
}
}
}
请问师哥们如何改!谢谢了~
[解决办法]
我封装的
/*
*
* CopyRight (C) 2006 Red_angelX Thanks [YoYo]
*/
using System;
using System.Net;
using System.Net.Sockets;
namespace QQClient.QQ.Connection
{
/// <summary>
/// Tcp连接类
///
/// @Author: Red_angelX
/// </summary>
class TcpConnection : IConnection
{
//远程主机信息
private IPEndPoint _remoteQQEP;
//Tcp客户端
private TcpClient _qqClient;
private int _qqServerIndex;
//收到的包
private byte[] RecvBuffer = new byte[2048];
/// <summary>
/// 托管事件
/// </summary>
public event RecvMsgEventHandler OnRecvMsg;
/// <summary>
/// 网络连接失败
/// </summary>
public event NetworkErrorEventHandler OnSocketError;
/// <summary>
/// 异步UDP接收函数
/// </summary>
/// <param name= "ar "> null </param>
private void ReceiveCallBack(IAsyncResult ar)
{
try
{
lock (this)
{
int recvCount = _qqClient.GetStream().EndRead(ar);
if (recvCount < 1)
{
if (OnSocketError != null)
{
_qqClient.Close();
OnSocketError(this, new EventArgs());
}
}
byte[] recvbytes = new byte[recvCount];
Array.Copy(RecvBuffer, 0, recvbytes, 0, recvCount);
//直接发送数据包到QQClient处理
OnRecvMsg(this, recvbytes);
}
lock (this)
{
//继续接收
_qqClient.GetStream().BeginRead(RecvBuffer, 0, 2048, new AsyncCallback(ReceiveCallBack), null);
}
}
catch (SocketException ex)
{
OnSocketError(this, new EventArgs());
}
catch (ObjectDisposedException)
{
/*
* 这个因该再BeginReceive之后通知
* 因为有可能OnRecvMsg调用DisPose导致异常
* 所以捕获这个异常什么也不做
*/
}
catch (Exception ex)
{
Util.LogDebug(ex.ToString());
}
}
/**************************************************
* 发送数据包,重载自接口 *
* ***********************************************/
public void Send(byte[] Packet)
{
try
{
//_qqClient.Ttl = 42;
_qqClient.GetStream().Write(Packet, 0, Packet.Length);
}
catch
{
OnSocketError(this, new EventArgs());
}
}
}
}
删除了一些代码 凑合着看接收部分吧
[解决办法]
//通信用的
Thread myThread;
UdpClient listener;
bool linkState;
string strReceive;
IPEndPoint groupEP;
//发送函数
private void f_send(string s_send)
{
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
//我
IPAddress broadcast = IPAddress.Parse( "192.168.200.21 ");
IPEndPoint ep = new IPEndPoint(broadcast, 11001);
////你
//IPAddress broadcast = IPAddress.Parse( "192.168.200.25 ");
//IPEndPoint ep = new IPEndPoint(broadcast, 11000);
byte[] sendbuf = Encoding.Unicode.GetBytes(s_send);
s.SendTo(sendbuf, ep);
s.Close();
}
//接收
public void UdpReceive()
{
//我
listener = new UdpClient(11000);
groupEP = new IPEndPoint(IPAddress.Any, 11000);
////你
//listener = new UdpClient(11001);
//groupEP = new IPEndPoint(IPAddress.Any, 11001);
linkState = true;
Control.CheckForIllegalCrossThreadCalls = false;
try
{
while (linkState)
{
byte[] bytes = listener.Receive(ref groupEP);
//strReceive = Encoding.ASCII.GetString(bytes, 0, bytes.Length);
strReceive = Encoding.Unicode.GetString(bytes, 0, bytes.Length);
if (strReceive == "#online# ")
{
i_online = 0;
if (b_icon_online == false)
{
f_set_icon_online();
b_icon_online = true;
}
}
else if (strReceive == "#notonline# ")
{
i_online = 3;
if (b_icon_online == true)
{
f_set_icon_not_online();
b_icon_online = false;
}
}
else
{
string[] s = strReceive.Split( '& ');
f_set_icon_new_message();
//声音提示
SoundPlay player = new SoundPlay();
player.play();
//弹出窗口
if (this.WindowState == FormWindowState.Normal)
{ }
else
{
System.Diagnostics.Process.Start(@Application.StartupPath + "\\send1_msg.exe ");
}
//f_writeHtml( "你: ", strReceive, "color: #000099; font-style: normal;font-weight: bold; ");
f_writeHtml( "你: ", s[0], s[1]);
}
}
}
catch { }
}
private void Form1_Load(object sender, EventArgs e)
{
myThread = new Thread(new ThreadStart(UdpReceive));
myThread.Start();
}