System.InvalidOperationException:'在未连接的套接字上不允许执行该操作。

时间:2018-06-21 07:30:23

标签: c#

这是我的表格

https://i.stack.imgur.com/M7fuy.png

这是我的代码

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    using System.Net.Sockets;

    namespace WindowsApplication1
    {
      public partial class Form1 : Form
       {
          System.Net.Sockets.TcpClient clientSocket = new 
                 System.Net.Sockets.TcpClient();
    //NetworkStream serverStream = default(NetworkStream);
    //string readData = null;
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        msg("Client Started");
        clientSocket.Connect("192.168.0.167", 5000);
        label1.Text = "Client Socket Program - Server Connected ...";
    }



    private void button1_Click(object sender, EventArgs e)
    {
        NetworkStream serverStream = clientSocket.GetStream();
        byte[] outStream = System.Text.Encoding.ASCII.GetBytes(textBox2.Text + "$");
        serverStream.Write(outStream, 0, outStream.Length);
        serverStream.Flush();

        byte[] inStream = new byte[10025];
        serverStream.Read(inStream, 0, (int)clientSocket.ReceiveBufferSize);
        string returndata = System.Text.Encoding.ASCII.GetString(inStream);
        msg(returndata);
        textBox2.Text = "";
        textBox2.Focus();

    }


    public void msg(string mesg)
    {
        textBox1.Text = textBox1.Text + Environment.NewLine + " >> " + mesg;
    }


}

}

当我单击代码中的开始按钮时,出现此错误以连接到服务器。请指导我如何摆脱此错误并改为连接服务器。

https://i.stack.imgur.com/wDSCI.png

0 个答案:

没有答案