套接字通信错误

本文关键字:错误 通信 套接字 | 更新日期: 2023-09-27 18:04:02

我正在用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端口,它已经连接。所以拜托,我的问题在哪里?我如何连接到每个端口?请忽略代码中的注释,请帮助我

套接字通信错误

您正在监听端口80,这是您的客户机程序应该连接到的端口。"1234"为服务器绑定的LOCAL端口。

服务器监听哪个IP ?你检查netstat -an | FIND"LISTEN"| FIND"1234"了吗?(注意:用你的语言表示代替listen…)

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

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

hth

马里奥