使用套接字在Web应用程序中聊天给我一个错误

时间:2012-01-04 06:32:25

标签: c# asp.net sockets

我尝试使用C#在asp.net中使用套接字。

客户端代码中的注释行给了我错误。

服务器代码正常运行。

这是给出错误的客户端代码。

   using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.Text;

public partial class _Default : System.Web.UI.Page
{
System.Net.Sockets.TcpClient clientSocket = new System.Net.Sockets.TcpClient();
NetworkStream serverStream = default(NetworkStream);
string readData = null;

protected void Page_Load(object sender, EventArgs e)
{



}

protected void Post_Click(object sender, EventArgs e)
{
    if (txtmsg.Text != "")
    {
        byte[] outStream = System.Text.Encoding.ASCII.GetBytes(txtmsg.Text + "$");
        serverStream.Write(outStream, 0, outStream.Length); 
        // This line gives error Saying Object reference not set to an instance of an object.
        serverStream.Flush();
    }


}
protected void Connect_Click(object sender, EventArgs e)
{
    if (txtSub.Text != "")
    {
        try
        {
            readData = "Conected to Chat Server ...";
            msg();
            clientSocket.Connect("127.0.0.1", 8888);
            serverStream = clientSocket.GetStream();

            byte[] outStream = System.Text.Encoding.ASCII.GetBytes(txtSub.Text + "$");
            serverStream.Write(outStream, 0, outStream.Length);
            serverStream.Flush();

            Thread ctThread = new Thread(getMessage);
            ctThread.Start();

        }
        catch
        {
            //Disconnect();
        }
    }
}

private void getMessage()
{
    while (true)
    {
        serverStream = clientSocket.GetStream();
        int buffSize = 0;
        byte[] inStream = new byte[10025];
        buffSize = clientSocket.ReceiveBufferSize;
        serverStream.Read(inStream, 0, buffSize);
        string returndata = System.Text.Encoding.ASCII.GetString(inStream);
        readData = "" + returndata;
        msg();
    }
}

private void msg()
{
    //if (this.InvokeRequired)
    //    this.Invoke(new MethodInvoker(msg));
    //else
    txtget.Text = txtget.Text + Environment.NewLine + " >> " + readData;
} 
}

1 个答案:

答案 0 :(得分:0)

您的serverSteam对象未正确初始化,因此在您尝试引用它时会导致对象错误。

您需要使用Socket对象创建一个新的NetworkSteam,并确保您的Socket对象已连接:

Socket my_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
..
// connect socket and any other operations
..
NetworkStream my_network_stream = new NetworkStream(my_socket);