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="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
<script language="c#" runat="server">
private static int port = 9050;
private static string serverip = "127.0.0.1";
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)
{
Run();
}
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);
}
ConnectionClosed(serverSckt);
}
private void Connecting(IPEndPoint ipep, Socket serverSckt)
{
try
{
serverSckt.Connect(ipep);
}
catch (SocketException ex)
{
Response.Write("Unable to Connect to server");
Response.Write(ex.ToString());
}
}
private void TcpSend(Socket server, string message)
{
server.Send(Encoding.ASCII.GetBytes(message));
}
private static void ConnectionClosed(Socket sockt)
{
sockt.Close();
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>