Click here to Skip to main content
15,305,517 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
i wrote a synchron tcp client socket which can just sending data,no receive.
the problem is socket just ont time send data and the next time i have this error:

"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."

i know the problem is because of while condition.but why?

<%@ Page Language="C#" AutoEventWireup="true" %>
<%@ Import Namespace="System"%>
<%@ Import Namespace="System.Net"%>
<%@ Import Namespace="System.Net.Sockets"%>
<%@ Import Namespace="System.Text"%>
<%@ Import Namespace="System.IO"%>
<!DOCTYPE html>
<html xmlns="">
<head id="Head1" runat="server">
    <script language="c#" runat="server"> 
        private static int port = 9050;
        private static string serverip = "";
        private static int timeoutHour = 0;
        private static int timeoutMin = 3;
        private static int timeoutScnd = 10;
        private static int timeoutMilScnd = 0;
        private static int BufferSize = 1024;
        private static byte[] data = new byte[BufferSize];
        private static string msg = "Hello";
        protected void Page_Load(object sender, EventArgs e)

        private void Run()
            IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(serverip), port);
            Socket serverSckt = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                       DateTime TimeAtStart = new DateTime();
                        TimeAtStart = DateTime.Now;
                        TimeSpan TimeOut = new TimeSpan(timeoutHour, timeoutMin, timeoutScnd,timeoutMilScnd);

                        while (TimeOut > (DateTime.Now - TimeAtStart))
                            Connecting(ipep, serverSckt);
                            TcpSend(serverSckt, msg);

        private void Connecting(IPEndPoint ipep, Socket serverSckt)
                serverSckt.Connect(ipep); //error is here
            catch (SocketException ex)
                Response.Write("Unable to Connect to server");
        private void TcpSend(Socket server, string message)
        private static void ConnectionClosed(Socket sockt)
    <form id="form1" runat="server">
vijay__p 7-May-13 2:04am
You should not keep connection socket again and again.
Put Connecting(ipep, serverSckt); out side of while loop.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900