English 中文(简体)
C# sent/receive fromocket
原标题:C# send/receive from socket
  • 时间:2011-03-24 08:47:45
  •  标签:
  • c#
  • sockets

我想从我的服务器上发送和接收一些数据,但我不知道如何这样做。

Basically I want to: Send: "some string" To: IP: 10.100.200.1 Port: 30000

Receive/read the response

难道有人会给我一些基本例子,或者把我说到简单的(工作)辅导?

最佳回答

简明扼要 TcpClient sent a text string and received a text string.

using System;
using System.IO;
using System.Net;
using System.Text;
using System.Net.Sockets;

public class SimpleTcpClient {

    public static void Main() {

        TcpClient tcpclnt = new TcpClient();            
        tcpclnt.Connect("10.100.200.1",30000);

        String textToSend = "HelloWorld!";
        Stream stm = tcpclnt.GetStream();

        ASCIIEncoding asen = new ASCIIEncoding();
        byte[] data = asen.GetBytes(textToSend);

        stm.Write(data,0,data.Length);

        //You might want to wait a bit for an answer (Thread.Sleep or simething)

        byte[] responseData = new byte[1024];
        string textRecevided = "";
        int read = 0;               
        do {  
            read = stm.Read(responseData, 0, responseData.Length);
            for (int i=0; i < read; i++)
            {
                textRecevided += (char)responseData[i];
            }           
        } while (read > 0);

        Console.Write(textRecevied);

        tcpclnt.Close();
    }

}
问题回答

你的问题范围很广,可以轻易地通过巡回回答。

您正在研究的是<代码>Socket/code>。 但就你的情况而言,我会使用<代码>TcpClient,因为它使处理更为容易。

页: 1 然后,如果你不能工作,就会再次提出更具体的问题。





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签