I created a Windows Form application that can connect to another one on the same PC but it won't work on the LAN , I used sockets but I didn't fully understood it and I am not that great at C#.
I have the following code for the server:
private byte[] _buffer = new byte[4096];
public List<SocketT2h> __ClientSockets { get; set; }
List<string> _names = new List<string>();
private Socket _serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
public Main()
{
InitializeComponent();
CheckForIllegalCrossThreadCalls = false;
__ClientSockets = new List<SocketT2h>();
}
private void Main_Load(object sender, EventArgs e)
{
contextMenuStrip1.ItemClicked += new ToolStripItemClickedEventHandler(contextMenuStrip1_ItemClicked);
SetupServer();
}
private void SetupServer()
{
Console_textBox.Text += "Setting up server . . .\n";
_serverSocket.Bind(new IPEndPoint(IPAddress.Any, 100));
_serverSocket.Listen(1);
_serverSocket.BeginAccept(new AsyncCallback(AppceptCallback), null);
Console_textBox.Text += "Server is online !";
}
private void AppceptCallback(IAsyncResult ar)
{
Socket socket = _serverSocket.EndAccept(ar);
__ClientSockets.Add(new SocketT2h(socket));
Console_textBox.Text = "Client connected. . .";
socket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), socket);
_serverSocket.BeginAccept(new AsyncCallback(AppceptCallback), null);
}
And this is the code for the client:
public Form1()
{
InitializeComponent();
LoopConnect();
_clientSocket.BeginReceive(receivedBuf, 0, receivedBuf.Length, SocketFlags.None, new AsyncCallback(ReceiveData), _clientSocket);
byte[] buffer = Encoding.ASCII.GetBytes("Alex : ");
_clientSocket.Send(buffer);
}
private Socket _clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
byte[] receivedBuf = new byte[4096];
private void ReceiveData(IAsyncResult ar)
{
try
{
Socket socket = (Socket)ar.AsyncState;
int received = socket.EndReceive(ar);
byte[] dataBuf = new byte[received];
Array.Copy(receivedBuf, dataBuf, received);
_clientSocket.BeginReceive(receivedBuf, 0, receivedBuf.Length, SocketFlags.None, new AsyncCallback(ReceiveData), _clientSocket);
}
catch { }
}
private void SendLoop()
{
while (true)
{
try
{
byte[] receivedBuf = new byte[4096];
int rev = _clientSocket.Receive(receivedBuf);
if (rev != 0)
{
byte[] data = new byte[rev];
Array.Copy(receivedBuf, data, rev);
}
else _clientSocket.Close();
}
catch { }
}
}
private void LoopConnect()
{
try
{
int attempts = 0;
while (!_clientSocket.Connected)
{
try
{
attempts++;
_clientSocket.Connect(IPAddress.Loopback, 100);
}
catch (SocketException)
{
}
}
}
catch { }
}
I also added the ports used by the Apps to the FireWall.
If I'm doing it completely wrong, I'm sorry, but I'm still learning.