Dzień dobry. Mam pewien problem, ponieważ Client nie chce połączyć się z serwerem. Kiedy serwer nasłuchuje na porcie np.: 8061 to ustawiam Clientowi ten sam port, ale jak kliknę przycisk submit, aby wysłać wiadomość na serwer pojawia się błąd:
System.Net.Sockets.SocketException: „Nie można nawiązać połączenia, ponieważ komputer docelowy aktywnie go odmawia 192.168.1.103:8061”
Client:
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
namespace client_tcp
{
public partial class Form1 : Form
{
public string serverIP = "192.168.1.103";
public int port = 8061;
public Form1()
{
InitializeComponent();
}
private void submit_Click(object sender, EventArgs e)
{
TcpClient client = new TcpClient(serverIP, port);
int byteCount = Encoding.ASCII.GetByteCount(message.Text);
byte[] sendData = new byte[byteCount];
sendData = Encoding.ASCII.GetBytes(message.Text);
NetworkStream stream = client.GetStream();
stream.Write(sendData, 0, sendData.Length);
stream.Close();
client.Close();
}
}
}
Serwer:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
namespace Program
{
class Program
{
static void Main(string[] args)
{
string adr;
Console.Write("IP Address: ");
adr = Console.ReadLine();
Console.Write("Port: ");
int port = Convert.ToInt32(Console.ReadLine());
IPAddress ip = Dns.GetHostEntry(adr).AddressList[0];
TcpListener server = new TcpListener(ip, port);
TcpClient client = default(TcpClient);
try
{
server.Start();
Console.WriteLine("Server started. No error was found...");
Console.Read();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
Console.Read();
}
while(true)
{
client = server.AcceptTcpClient();
byte[] receivedBuffer = new byte[100];
NetworkStream stream = client.GetStream();
stream.Read(receivedBuffer, 0, receivedBuffer.Length);
string msg = Encoding.ASCII.GetString(receivedBuffer, 0, receivedBuffer.Length);
Console.WriteLine(msg);
Console.Read();
}
}
}
}