【问题标题】:Socket communication error套接字通信错误
【发布时间】:2011-07-28 10:51:31
【问题描述】:

我正在用 C# 编写用于套接字通信的小程序。这是我的代码: 客户端(数据发送者):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;

namespace Client
{
class Program
{
    static Socket sck; //vytvor socket
    static void Main(string[] args)
    {
        sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 1234); //nastav premennú loacalEndPoint na lokálnu ip a port 1234
        try  //Skús sa
        {
            sck.Connect(localEndPoint); // pripojiť

        }
        catch { //ak sa to nepodarí
            Console.Write("Unable to connect to remote ip end point \r\n"); //vypíš chybovú hlášku
            Main(args);
        }

        Console.Write("Enter text: ");
        string text = Console.ReadLine();
        byte[] data = Encoding.ASCII.GetBytes(text);
        sck.Send(data);
        Console.Write("Data sent!\r\n");
        Console.Write("Press any key to continue...");
        Console.Read();
        sck.Close();
    }
}
}

服务器(数据接收器):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;


namespace Server
{
class Program
{
    static byte[] Buffer { get; set; } //vytvor Buffer
    static Socket sck;

    static void Main(string[] args)
    {
        sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //vytvor Socket
        sck.Bind(new IPEndPoint(0, 1234));
        sck.Listen(80);
        Socket accepted = sck.Accept();
        Buffer = new byte[accepted.SendBufferSize];
        int bytesRead = accepted.Receive(Buffer);
        byte[] formatted = new byte[bytesRead]; //vytvor novú Array a jej dĺžka bude dĺžka priatých infomácii
        for(int i=0; i<bytesRead;i++){
            formatted[i] = Buffer[i]; //načítaj z Buffer do formatted všetky priate Bajty

        }
        string strData = Encoding.ASCII.GetString(formatted); //z ASCII hodnôt urob reťazec
        Console.Write(strData + "\r\n"); //vypíš data
        sck.Close(); //ukonči spojenie


    }
}

} 我的问题是:在客户端程序中,我将端口 1234 上的数据发送到本地 ip。但我无法连接。我试过80端口,它已经连接了。那么请问,我的问题在哪里?如何连接到每个人的端口?请忽略代码中的 cmets,请帮助我。

【问题讨论】:

  • 这些程序在安装时注册(解锁)端口。
  • 我现在不工作。我有代码,我关闭了所有防火墙。哪里有问题?

标签: c# visual-studio sockets connection port


【解决方案1】:

您正在侦听端口 80,这是您的客户端程序应连接的端口。 “1234”是服务器绑定的本地端口。该端口上没有任何东西在监听。

【讨论】:

    【解决方案2】:

    服务器在哪个 ip 上监听?你用 netstat -an 检查了吗?寻找“听” |找到“1234”? (注意:用你的语言表示替换listen ...)。

    0 可能不是 127.0.0.1 而是第一个 NIC 的第一个分配 IP 地址...(虽然 0 应该监听所有接口...但是唉...

    我总是在客户端和服务器中都使用 IP 地址

    马里奥

    【讨论】:

      猜你喜欢
      • 2014-06-30
      • 1970-01-01
      • 2017-08-03
      • 1970-01-01
      • 1970-01-01
      • 2020-06-19
      • 1970-01-01
      • 1970-01-01
      • 2015-10-24
      相关资源
      最近更新 更多