Я пытался использовать сокеты в asp.net, используя C #.
Закомментированная строка в коде клиента выдает ошибку.
Код сервера работает правильно.
Это код клиента, который выдает ошибку.
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;
}
}