简体   繁体   中英

Sending Json format message from a c# application to server

I have a .Net framework Project(c#).I have a form in the project(shown in the picture) 在此处输入图片说明

.Following a documentation that was prepared for me, I am supposed to use either websocket or socket and write the message in the bottom textbox following a Json Format(I dont have to convert using newtonsoft) to be able to send the message to an ip address.

However I am confused as to whether would tcpclient/tcplistener work as well.(The code shown below is the one that I have tried implementing)

     Public partial class Form1 : Form
    {
    TcpClient clientsocket=new tcpclient();
    public Form1()
    {
    InitializeComponent();
    }
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[4096];
            //int bytesread = serverStream.Read(inStream, 0, inStream.Length);
            //string returndata = System.Text.Encoding.ASCII.GetString(inStream, 0, bytesread);
            //msg(returndata);
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            msg("Client Started");
           // server.Connect(IPEP);
            clientSocket.Connect(IPAddress.Parse("000.0.0.1"), 8080);
            label1.Text = "Connected Value is {0} "+ clientSocket.Connected;
            Console.WriteLine("Connected Value is {0}", clientSocket.Connected);
        }
        public void msg(string mesg)
        {
            textBox1.Text = textBox1.Text + Environment.NewLine + " >> " + mesg;
        } 
    }

I have tried running the program, while typing { "msg_id":"ROBOT_BODY_CTRL_CMD", "body_part":2, "action":3 } however nothing happens. Since I am sending a message, am I acting as a client or the server?

When you send a message to any ip address on specific socket you are client and when you receive message while listening to any port you are acting as server

here is Microsoft Official Examples on Synchronous an Asynchronous Socket Programming

Socket Code Examples

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM