我使用Windows7和VS2010编写一个C#winform程序。
在程序中,我运行启动TCP套接字服务器和套接字客户端。接受客户端套接字后,我将命令发送给客户端。
当我发送数据时,发生错误:System.NullReferenceException.
在此行:
myClientSocket.Send(bs3, bs3.Length, 0);
我已经调试了程序,套接字服务器和客户端可以成功创建。客户端也可以成功连接到服务器。我认为myclientsocket可能不存在,因此无法发送命令。但是我不知道为什么。 代码:
public partial class Form1 : Form
{
public static Socket myClientSocket = null;
protected override void OnLoad(EventArgs e)
{
SocketServie();
Thread.Sleep(1000);
runclient();
Thread.Sleep(2000);
read();
}
public void SocketServie()
{
string host = "127.0.0.1";
int port = 8024;
socket.SetSocketOption(SocketOptionLevel.Socket,
SocketOptionName.ReuseAddress, true); //port reuse
socket.Bind(new IPEndPoint(IPAddress.Parse(host), port));
socket.Listen(100);
Thread SocketThread = new Thread(this.ListenClientConnect);
SocketThread.IsBackground = true;
SocketThread.Start();
}
private void ListenClientConnect()
{
while (true)
{
this.clientSocket = socket.Accept();
Thread receiveThread = new Thread(new
ParameterizedThreadStart(ReceiveMessage));
receiveThread.IsBackground = true;
receiveThread.Start(this);
Thread.Sleep(1000);
}
}
public void ReceiveMessage(object Form1)
{
Form2 f5 = new Form2();
//Socket myClientSocket = (Socket)clientSocket;
myClientSocket = (Socket)clientSocket;
string InitCurMeter = "INIT_CUR_METER\r\n";
byte[] bs = Encoding.UTF8.GetBytes(InitCurMeter);
myClientSocket.Send(bs, bs.Length, 0);
Thread.Sleep(2000);
string InitVolMeter = "INIT_VOL_METER\r\n";
byte[] bs2 =
Encoding.UTF8.GetBytes(InitVolMeter);//Encoding.UTF8.GetBytes()
myClientSocket.Send(bs2, bs2.Length, 0);
}
public void runclient(object sender, EventArgs e)
{
try
{
using (Process myProcess = new Process())
{
myProcess.StartInfo.UseShellExecute = false;
myProcess.StartInfo.FileName = "socket_client.exe";
myProcess.StartInfo.Arguments = "-p 8024";
myProcess.StartInfo.CreateNoWindow = true;
myProcess.Start();
}
}
catch (Exception error)
{
}
}
public static void read()
{
try
{
string readCurMeter = "READ\r\n";
byte[] bs3 = Encoding.UTF8.GetBytes(readCurMeter);
myClientSocket.Send(bs3, bs3.Length, 0);
}
catch (Exception e5)
{
MessageBox.Show("read_cur error:" + e5.Message);
}
}
}