[英]Socket communication error
我正在用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檢查了嗎? 找到“LISTEN”| 找到“1234”? (注意:用你的語言表示代替聽......)。
0可能不是127.0.0.1但是第一個分配給第一個NIC的IP地址...(雖然0應該監聽所有接口......但是...
我總是在客戶端和服務器中都使用IP地址
心連心
馬里奧
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.