I'm making small program for socket communication in C#. Here're my codes: Client (data sender):
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();
}
}
}
Server (data 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
}
}
} My problem is: In client program I'm sending data on port 1234 to local ip. But I cannot c开发者_C百科onnect. I have tried port 80 and it has connected. So please, where's my problem? How can I connect to everyone port? Please ignore comments in code and please help me.
You're listening on port 80, that is the port your client program should connect to. The "1234" is the LOCAL port the server is bound to. Nothing is listening on that port.
on which ip does the server listen? did you check with netstat -an | FIND "LISTEN" | FIND "1234"? (Note: replace listen with you language representation of it...).
0 may not be 127.0.0.1 but the first assigned IP adress of the first NIC... (although 0 should listen to all interfaces... but alas...
I would always use IP-adresses in both, the client and the server
hth
Mario
精彩评论