socket客户端接收有值但是不能显示出数据
yzone 2009-11-04 10:04:25 小弟在做SOCKET聊天,客户端用.NET,服务器端用WINFORM,在调式当中遇见了一个问题,在客户端不能显示出数据,但是传过来说有值的,太奇怪了, /// <summary>
/// 登录聊天连接
/// </summary>
public void EstablishConnection()
{
DivLiaoTian.InnerText = "正在连接到服务器";
try
{
clientsocket = new TcpClient(serveraddress, serverport); //建立连接
ns = clientsocket.GetStream();//接收返回的数据
sr = new StreamReader(ns); //读取流
connected = true; //连接状态为连接
}
catch (Exception)
{
DivLiaoTian.InnerText = "不能连接服务器";
}
}
/// <summary>
/// 和服务器交互
/// </summary>
public void RegisterWithServer()
{
clientname = this.lblname.Text;//获取用户的昵称
try
{
string command = "CONN|" + clientname; //+"\r\n";
Byte[] outbytes = System.Text.Encoding.UTF8.GetBytes(command.ToCharArray());//转化
ns.Write(outbytes, 0, outbytes.Length); //写入流
string serverresponse = sr.ReadLine(); //读取流
serverresponse.Trim();
string[] tokens = serverresponse.Split('|');
if (tokens[0] == "LIST")
{
DivLiaoTian.InnerText = "已连接到服务器";
}
}
catch (Exception ex)
{
DivLiaoTian.InnerText = "连接失败";
connected = false;
}
}//发送数据
private void ReceiveChat()
{
bool keepalive = true;
while (keepalive)
{
try
{
Byte[] buffer = new Byte[102400];
ns.Read(buffer, 0, buffer.Length);//读取流
string chatter = System.Text.Encoding.UTF8.GetString(buffer);
string[] tokens = chatter.Split(new Char[] { '|' });
if (tokens[0] == "CHAT")//公聊
{
inpSiLiaoUserName.Value = tokens[1]; [
//mi.BeginInvoke(tokens[1], null, null);
//mi.Invoke(tokens[1]);
//mi.BeginInvoke(tokens[1], mi, new object[] {tokens[1]});
//this.BeginInvoke(mi, new object[] {tokens[1]});
// this.txt111.Text = tokens[1];
}
if (tokens[0] == "PRIV")//私聊
{
//rtbChatIn.AppendText("Private from ");
// rtbChatIn.AppendText(tokens[1].Trim());
//rtbChatIn.AppendText(tokens[2] + "\r\n");
}
if (tokens[0] == "JOIN")//加入
{
//rtbChatIn.AppendText(tokens[1].Trim());
//rtbChatIn.AppendText(" has joined the Chat\r\n");
//string newguy = tokens[1].Trim(new char[] { '\r', '\n' });
//lbChatters.Items.Add(newguy);
}
if (tokens[0] == "GONE") //离开
{
//rtbChatIn.AppendText(tokens[1].Trim());
//rtbChatIn.AppendText(" has left the Chat\r\n");
//lbChatters.Items.Remove(tokens[1].Trim(new char[] { '\r', '\n' }));
}
if (tokens[0] == "QUIT")//服务器已停止
{
ns.Close(); //关闭流
clientsocket.Close();//监听关闭
keepalive = false; //在线状态
DivLiaoTian.InnerText += "服务器端已停止";
connected = false; //链接停止
}
}
catch (Exception) { }
}
}就是注释的那句,TOKEN[1]里面有值不能显示,请大家帮忙