有一个主机开放了一个端口,若向他提交一个字符串,则返回一个计算后的字符串请问在C#里怎么实现发送和接受  头一次接触这个 请给个示范代码 谢了!

解决方案 »

  1.   

    使用System.Net.Sockets名字空间中的Socket类应该就可以了大致的步骤是这样的:
    1. 先生成一个Socket类
    2. 调用该类的Socket方法
    3. 调用Send方法
    4. 再调用Receive方法就可以了这是同步的步骤,如果使用异步就要麻烦一些
      

  2.   

    服务器      客户端
    bind
    listen
    accept      connect
    receive     send
    send        receive大概就是这样
      

  3.   

    我也刚学 楼上的说得很好了 如果还不行就看看MSDN 
    接受: try
                    {                    while (true)
                        {                        Byte[] ByteRecv = new Byte[256];
                            this.mySocket.Receive(ByteRecv);
                         
                            string strRecv = Encoding.BigEndianUnicode.GetString(ByteRecv);
                           
                  
                            if (this.rtbReceive.InvokeRequired)
                            {                            this.rtbReceive.Invoke(new EventHandler(ChangeRtb), new object[] { strRecv, EventArgs.Empty });                        }
                            else
                            {
                                this.rtbReceive.AppendText(strRecv + "\r\n");
                            }
                        }
                    }
                    catch (Exception ex)
                    {                    MessageBox.Show("Receive Message Error" + ex.Message);
    发送:
    private void btnSend_Click(object sender, EventArgs e)
            {
               
                try
                {
                   // Server = new IPEndPoint(((IPEndPoint)sockets[0].RemoteEndPoint).Address, ((IPEndPoint)sockets[2].RemoteEndPoint).Port);
                    string strSend = "Server--->" + rtbSend.Text + "\r\n";
                    Byte[] ByteSend = Encoding.BigEndianUnicode.GetBytes(strSend);
                    mySocket.Send(ByteSend);
                   
                }
                catch { MessageBox.Show("连接尚未建立,无法发送."); }
                
            }
      

  4.   

    看看 msdn,上面有例子,挺容易的。
      

  5.   

    我也喜欢参于这个讨论.  MSDN有简单的通信例子的.
    我就是搞不懂 
    不在同一 局域网.怎么通信的.
    例如: 家里局域网的一台机器  和 公司里局域网的一台机器.怎么用socket 通信.
    需要看哪些资料?
      

  6.   

    Socket 类为网络通信提供了一套丰富的方法和属性。Socket 类允许您使用 ProtocolType 枚举中所列出的任何一种协议执行异步和同步数据传输。Socket 类遵循异步方法的 .NET Framework 命名模式;例如,同步 Receive 方法对应于异步 BeginReceive 和 EndReceive 方法。如果应用程序在执行期间只需要一个线程,请使用下面的方法,这些方法适用于同步操作模式。 如果当前使用的是面向连接的协议(如 TCP),则服务器可以使用 Listen 方法侦听连接。Accept 方法处理任何传入的连接请求,并返回可用于与远程主机进行数据通信的 Socket。可以使用此返回的 Socket 来调用 Send 或 Receive 方法。如果要指定本地 IP 地址和端口号,请在调用 Listen 方法之前先调用 Bind 方法。如果不调用 Bind,基础服务提供程序将为您分配这些值。此后,可以使用 LocalEndPoint 属性来标识分配给 Socket 的 IP 地址和端口号。如果想连接到侦听主机,请调用 Connect 方法。若要进行数据通信,请调用 Send 或 Receive 方法。 
    如果当前使用的是无连接协议(如 UDP),则根本不需要侦听连接。调用 ReceiveFrom 方法可接受任何传入的数据报。使用 SendTo 方法可将数据报发送到远程主机。 
    若要在执行过程中使用单独的线程处理通信,请使用下面的方法,这些方法适用于异步操作模式。 如果当前使用的是面向连接的协议(如 TCP),则可使用 Socket、BeginConnect 和 EndConnect 方法来连接侦听主机。通过使用 BeginSend 和 EndSend 方法,或者使用 BeginReceive 和 EndReceive 方法,可以进行异步数据通信。可以使用 BeginAccept 和 EndAccept 处理传入的连接请求。 
    如果当前使用的是无连接协议(如 UDP),则可以使用 BeginSendTo 和 EndSendTo 来发送数据报,而使用 BeginReceiveFrom 和 EndReceiveFrom 来接收数据报。 
    如果对一个套接字执行多个异步操作,它们不一定按启动时的顺序完成。当数据发送和数据接收完成之后,可使用 Shutdown 方法来禁用 Socket。在调用 Shutdown 之后,可调用 Close 方法来释放与 Socket 关联的所有资源。Socket 类允许使用 SetSocketOption 方法来配置 Socket。可使用 GetSocketOption 方法来检索这些设置。注意   如果编写较简单的应用程序,而且只需同步数据传输,则可以考虑使用 TcpClient、TcpListener 和 UdpClient。这些类为 Socket 通信提供了更简单、对用户更友好的接口。[C#] 
    using System;
    using System.Text;
    using System.IO;
    using System.Net;
    using System.Net.Sockets;public class GetSocket
    {
        private static Socket ConnectSocket(string server, int port)
        {
            Socket s = null;
            IPHostEntry hostEntry = null;
            
            // Get host related information.
            hostEntry = Dns.Resolve(server);        // Loop through the AddressList to obtain the supported AddressFamily. This is to avoid
            // an exception that occurs when the host IP Address is not compatible with the address family
            // (typical in the IPv6 case).
            foreach(IPAddress address in hostEntry.AddressList)
            {
                IPEndPoint ipe = new IPEndPoint(address, port);
                Socket tempSocket = 
                    new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp);            tempSocket.Connect(ipe);            if(tempSocket.Connected)
                {
                    s = tempSocket;
                    break;
                }
                else
                {
                    continue;
                }
            }
            return s;
        }    // This method requests the home page content for the specified server.
        private static string SocketSendReceive(string server, int port) 
        {
            string request = "GET / HTTP/1.1\r\nHost: " + server + 
                "\r\nConnection: Close\r\n\r\n";
            Byte[] bytesSent = Encoding.ASCII.GetBytes(request);
            Byte[] bytesReceived = new Byte[256];
           
            // Create a socket connection with the specified server and port.
            Socket s = ConnectSocket(server, port);        if (s == null)
                return ("Connection failed");
          
            // Send request to the server.
            s.Send(bytesSent, bytesSent.Length, 0);  
            
            // Receive the server home page content.
            int bytes = 0;
            string page = "Default HTML page on " + server + ":\r\n";        // The following will block until te page is transmitted.
            do {
                bytes = s.Receive(bytesReceived, bytesReceived.Length, 0);
                page = page + Encoding.ASCII.GetString(bytesReceived, 0, bytes);
            }
            while (bytes > 0);
            
            return page;
        }
        
        public static void Main(string[] args) 
        {
            string host;
            int port = 80;        if (args.Length == 0)
                // If no server name is passed as argument to this program, 
                // use the current host name as the default.
                host = Dns.GetHostName();
            else
                host = args[0];        string result = SocketSendReceive(host, port); 
            Console.WriteLine(result);
        }
    }
    详细请参考:http://msdn.microsoft.com/library/chs/default.asp?url=/library/CHS/cpref/html/frlrfsystemnetsocketssocketclasstopic.asp