我在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();
}
}
}
服務器(數據reciver):
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,它已連接。所以,請問我的問題在哪裏?我怎樣才能連接到每個人的端口?請忽略代碼中的評論,並請幫助我。
檢查你的防火牆。 – Odys
這些程序寄存器(解鎖)端口,當你安裝它們。 – Odys
我現在不工作,我有一些代碼,並且我擁有所有防火牆關閉。哪裏可以成爲問題? – FrewCen