Hello, I am trying to create program, which will send data with TCP. First connect and sending is all right, but if I try to connect to other IP, then it doesn't work.
public Form1()
{
vlakno = new Thread(server); //for listening
vlakno.IsBackground = true;
vlakno.Start();
InitializeComponent();
adresa = IPAddress.Parse("127.0.0.1"); //first connect, it works when it isn't local too
client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
pripojeni();
}
public void pripojeni() //connect
{
if (client.Connected == true)
{
Odesli("Konec/prenosu/tcp/orientace = tcp.aa.fc.des.er"); //send mesage about end of connect
client.Shutdown(SocketShutdown.Both);
client.Disconnect(true);
}
IPEndPoint ipEndPoint = new IPEndPoint(adresa, 2000);
zmena = true;
Thread.Sleep(2000);
client.Connect(ipEndPoint); //here is an error in second connect
}
private void server()
{
poslouchany = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
local = new IPEndPoint(IPAddress.Any, 2000);
poslouchany.Bind(local);
poslouchany.Listen(100);
mag = new byte[100];
spojeni = poslouchany.Accept();
spojeni.BeginReceive(mag, 0, 100, SocketFlags.None, new AsyncCallback(Prijem), spojeni);
}
public void Prijem(IAsyncResult ar)
{
Socket socket = ar.AsyncState as Socket;
ASCIIEncoding kodovani = new ASCIIEncoding();
int bytesRead = socket.EndReceive(ar);
text = kodovani.GetString(mag);
if (text == "Konec/prenosu/tcp/orientace = tcp.aa.fc.des.er\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0") //if disconecting
{
spojeni.Close();
spojeni = null;
spojeni = poslouchany.Accept();
}
mag = null;
mag = new byte[100];
spojeni.BeginReceive(mag, 0, 100, SocketFlags.None, new AsyncCallback(Prijem), spojeni);
}
If there is a new connect, then addresa will be changed and I will try to connect to other IP, but client.Connect say: "Once the socket has been disconnected, you can only reconnect again asynchronously, and only to a different EndPoint. BeginConnect must be called on a thread that won't exit until the operation has been completed."
Normally when I shut down my connection I dispose of the socket. When I want to connect I create a new socket. Never really had any issues using this approach.
#1 You have not posted a complete source code listing. Please zip your code and post it. Otherwise we have to do more work than necessary to help you, and most don't want to.
#2 Have you either disabled your windows firewall / firewall or made an exception in the firewall?
It's OK now. In method pripojeni at the end must be:
client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
client.Connect(ipEndPoint);
I think, it work now, thank
Bookmarks