socket exception

Please support our C# advertiser: Intel Parallel Studio Home
Reply

Join Date: Oct 2009
Posts: 22
Reputation: bk_bhupendra is an unknown quantity at this point 
Solved Threads: 1
bk_bhupendra bk_bhupendra is offline Offline
Newbie Poster

socket exception

 
0
  #1
27 Days Ago
hi ,

i am doing a project in C#, windows application.
i am using sockets for communication between systems.

now i am facing an error...
its given below..
pls help me to solve this


  1. System.Net.Sockets.SocketException was unhandled
  2. Message="Only one usage of each socket address (protocol/network address/port) is normally permitted"
  3. Source="System"
  4. ErrorCode=10048
  5. NativeErrorCode=10048
  6. StackTrace:
  7. at System.Net.Sockets.Socket.DoBind(EndPoint endPointSnapshot, SocketAddress socketAddress)
  8. at System.Net.Sockets.Socket.Bind(EndPoint localEP)
  9. at FTServerCode..ctor() in F:\BK1\projects asp\Lan Chatting sockets\Async_client\Connect.cs:line 1063
  10. at AsyncClient.Connect..ctor() in F:\BK1\projects asp\Lan Chatting sockets\Async_client\Connect.cs:line 512
  11. at AsyncClient.HOME.field_Click(Object sender, EventArgs e) in F:\BK1\projects asp\Lan Chatting sockets\Async_client\HOME.cs:line 138
  12. at System.Windows.Forms.Control.OnClick(EventArgs e)
  13. at DevExpress.XtraEditors.BaseButton.OnClick(EventArgs e)
  14. at DevExpress.XtraEditors.BaseButton.OnMouseUp(MouseEventArgs e)
  15. at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
  16. at System.Windows.Forms.Control.WndProc(Message& m)
  17. at DevExpress.Utils.Controls.ControlBase.WndProc(Message& m)
  18. at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
  19. at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
  20. at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
  21. at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
  22. at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
  23. at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
  24. at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
  25. at System.Windows.Forms.Application.Run(Form mainForm)
  26. at AsyncClient.LAN_Chatting.Main() in F:\BK1\projects asp\Lan Chatting sockets\Async_client\LAN Chatting.Designer.cs:line 27
  27. at System.AppDomain.nExecuteAssembly(Assembly assembly, String[] args)
  28. at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
  29. at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
  30. at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
  31. at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
  32. at System.Threading.ThreadHelper.ThreadStart()
Last edited by peter_budo; 27 Days Ago at 12:36 pm. Reason: Keep It Organized - For easy readability, always wrap programming code within posts in [code] (code blocks)
Reply With Quote Quick reply to this message  
Join Date: Feb 2009
Posts: 3,252
Reputation: sknake has much to be proud of sknake has much to be proud of sknake has much to be proud of sknake has much to be proud of sknake has much to be proud of sknake has much to be proud of sknake has much to be proud of sknake has much to be proud of sknake has much to be proud of sknake has much to be proud of 
Solved Threads: 579
Sponsor
sknake's Avatar
sknake sknake is online now Online
.NET Enthusiast
 
0
  #2
27 Days Ago
Please use code tags when pasting data on daniweb. In the case of stack traces you can use plain text:

[code=text]
...stack trace here...
[/code]


You need to post the code where you're binding the socket. It looks like you're opening a socket to listen for an inbound connection twice with the same listen port.

There are the files you should post so we can answer your question:
F:\BK1\projects asp\Lan Chatting sockets\Async_client\HOME.cs
F:\BK1\projects asp\Lan Chatting sockets\Async_client\Connect.cs

Developer express controls rock!
Scott Knake
Custom Software Development
Apex Software, Inc.
Reply With Quote Quick reply to this message  
Join Date: Oct 2009
Posts: 22
Reputation: bk_bhupendra is an unknown quantity at this point 
Solved Threads: 1
bk_bhupendra bk_bhupendra is offline Offline
Newbie Poster

socket exception

 
0
  #3
27 Days Ago
F:\BK1\projects asp\Lan Chatting sockets\Async_client\HOME.cs

  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Text;
  7. using System.Windows.Forms;
  8. using DevExpress.XtraEditors;
  9.  
  10. namespace AsyncClient
  11. {
  12. public partial class HOME : DevExpress.XtraEditors.XtraForm
  13. {
  14. public string username;
  15. public HOME()
  16. {
  17.  
  18. InitializeComponent();
  19.  
  20. }
  21.  
  22.  
  23.  
  24. private void label1_Click(object sender, EventArgs e)
  25. {
  26.  
  27. this.Close();
  28. LAN_Chatting frm = new LAN_Chatting();
  29. frm.Show();
  30. }
  31.  
  32. private void HOME_Load(object sender, EventArgs e)
  33. {
  34. //label3.Text = username;
  35. }
  36.  
  37. private void connectToolStripMenuItem_Click(object sender, EventArgs e)
  38. {
  39. Connect frm = new Connect();
  40. frm.Show();
  41. }
  42.  
  43. private void fileRecievingPathToolStripMenuItem_Click(object sender, EventArgs e)
  44. {
  45.  
  46. }
  47.  
  48. private void menuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
  49. {
  50.  
  51. }
  52.  
  53. private void viewFriendsListToolStripMenuItem_Click(object sender, EventArgs e)
  54. {
  55.  
  56. }
  57.  
  58. private void editFriendsListToolStripMenuItem_Click(object sender, EventArgs e)
  59. {
  60. FriendList frm = new FriendList();
  61. frm.Show();
  62. }
  63.  
  64.  
  65. }
  66. }


F:\BK1\projects asp\Lan Chatting sockets\Async_client\Connect.cs

  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Text;
  7. using System.Windows.Forms;
  8. using DevExpress.XtraEditors;
  9. using System.Collections;
  10. using System.Net;
  11. using System.Net.Sockets;
  12. using System.IO;
  13.  
  14.  
  15. namespace AsyncClient
  16. {
  17. public partial class Connect : System.Windows.Forms.Form
  18. {
  19. public string client_ip;
  20. byte[] m_DataBuffer = new byte[10];
  21. IAsyncResult m_asynResult;
  22. public AsyncCallback pfnCallBack;
  23. public Socket m_socClient;
  24.  
  25.  
  26. public AsyncCallback pfnWorkerCallBack;
  27. public Socket m_socListener;
  28. public Socket m_socWorker;
  29.  
  30. private System.Windows.Forms.TextBox txtPort;
  31. private System.Windows.Forms.Button cmdSend;
  32. private System.Windows.Forms.GroupBox groupBox3;
  33. private System.Windows.Forms.Button cmdConnect;
  34. private System.Windows.Forms.Button cmdClose;
  35. private System.Windows.Forms.TextBox txtIPAddr;
  36.  
  37. int port;
  38. string file;
  39.  
  40. public Connect()
  41. {
  42. InitializeComponent();
  43. FTServerCode.receivedPath = "";
  44. }
  45. private void EnableCommands(bool abEnableConnect)
  46. {
  47.  
  48. button1.Enabled = abEnableConnect;
  49. }
  50. public class CSocketPacket
  51. {
  52. public System.Net.Sockets.Socket thisSocket;
  53. public byte[] dataBuffer = new byte[1];
  54. }
  55. private void button1_Click(object sender, EventArgs e)
  56. {
  57. try
  58. {
  59.  
  60. EnableCommands(true);
  61. //create the socket instance...
  62. m_socClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  63.  
  64. // get the remote IP address...
  65. client_ip = comboBox1.SelectedItem.ToString();
  66. string myIP = System.Net.Dns.GetHostByName(comboBox1.SelectedItem.ToString()).AddressList[0].ToString();
  67. IPAddress ip = IPAddress.Parse(myIP);
  68. /* if (comboBox2.SelectedItem.Equals("Default"))
  69.   {
  70.   port = 8221;
  71.   }
  72.   else
  73.   MessageBox.Show("Port not available");*/
  74. int iPortNo = 8444;
  75. //create the end point
  76. IPEndPoint ipEnd = new IPEndPoint(ip.Address, iPortNo);
  77. //connect to the remote host...
  78. m_socClient.Connect(ipEnd);
  79. EnableCommands(false);
  80. //watch for data ( asynchronously )...
  81. //groupBox1.Visible = false;
  82. groupBox2.Visible = true;
  83. WaitForData();
  84. //Chat_Window frm = new Chat_Window();
  85. //frm.Show();
  86. }
  87. catch (SocketException se)
  88. {
  89.  
  90. MessageBox.Show(se.Message);
  91. EnableCommands(true);
  92. }
  93. }
  94.  
  95. private void button2_Click(object sender, EventArgs e)
  96. {
  97. if (m_socClient != null)
  98. {
  99. //m_socClient.Shutdown (SocketShutdown.Send);
  100. m_socClient.Close();
  101. m_socClient = null;
  102. EnableCommands(true);
  103. MessageBox.Show("All Connections are Disconnected");
  104.  
  105. }
  106. }
  107.  
  108.  
  109. private void button4_Click(object sender, EventArgs e)
  110. {
  111. try
  112. {
  113. Object objData = textBox2.Text;
  114.  
  115. textBox1.Text = textBox1.Text + "\r\nME-> " + textBox2.Text + "\r\n";
  116. textBox2.Text = "";
  117.  
  118.  
  119. byte[] byData = System.Text.Encoding.ASCII.GetBytes(objData.ToString());
  120. m_socClient.Send(byData);
  121.  
  122. }
  123. catch (SocketException se)
  124. {
  125. MessageBox.Show(se.Message);
  126. }
  127. }
  128. /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  129. //File
  130. private void button5_Click(object sender, EventArgs e)
  131. {
  132. openFileDialog1.Title = "Open your File";
  133. //openFileDialog1.ShowDialog();
  134. if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
  135. {
  136. file = openFileDialog1.FileName.ToString();
  137. }
  138.  
  139.  
  140. try
  141. {
  142. IPAddress[] ipAddress = Dns.GetHostAddresses("localhost");
  143. IPEndPoint ipEnd = new IPEndPoint(ipAddress[0], 5656);
  144.  
  145. /* Make IP end point same as Server. */
  146. Socket clientSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
  147. /* Make a client socket to send data to server. */
  148.  
  149. string filePath = "";
  150. /* File reading operation. */
  151. file = file.Replace("\\", "/");
  152. while (file.IndexOf("/") > -1)
  153. {
  154. filePath += file.Substring(0, file.IndexOf("/") + 1);
  155. file = file.Substring(file.IndexOf("/") + 1);
  156. }
  157.  
  158.  
  159. byte[] fileByte = Encoding.ASCII.GetBytes(file);
  160. if (fileByte.Length > 850 * 1024)
  161. {
  162. //curMsg = "File size is more than 850kb, please try with small file.";
  163. return;
  164. }
  165.  
  166. // curMsg = "Buffering ...";
  167. byte[] fileData = File.ReadAllBytes(filePath + file);
  168.  
  169. /* Read & store file byte data in byte array. */
  170. byte[] clientData = new byte[4 + fileByte.Length + fileData.Length];
  171.  
  172. /* clientData will store complete bytes which will store file name length, file name & file data. */
  173. byte[] fileLen = BitConverter.GetBytes(fileByte.Length);
  174. /* File name length’s binary data. */
  175. fileLen.CopyTo(clientData, 0);
  176. fileByte.CopyTo(clientData, 4);
  177. fileData.CopyTo(clientData, 4 + fileByte.Length);
  178. /* copy these bytes to a variable with format line [file name length][file name] [ file content] */
  179. // curMsg = "Connection to server ...";
  180. clientSock.Connect(ipEnd);
  181.  
  182. //Trying to connection with server. /
  183.  
  184. // curMsg = "File sending...";
  185. clientSock.Send(clientData);
  186. /* Now connection established, send client data to server. */
  187. //curMsg = "Disconnecting...";
  188. clientSock.Close();
  189.  
  190. /* Data send complete now close socket. */
  191. // curMsg = "File transferred.";
  192.  
  193. }
  194. catch (Exception ex)
  195. {
  196. //if(ex.Message=="No connection could be made because the target machine actively refused it")
  197. // curMsg="File Sending fail. Because server not running." ;
  198. //else
  199. // curMsg = "File Sending fail." + ex.Message;
  200. }
  201.  
  202. }
  203. /// <summary>
  204. /// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  205. /// </summary>
  206. /// <param name="sender"></param>
  207. /// <param name="e"></param>
  208. private void button7_Click(object sender, EventArgs e)
  209. {
  210.  
  211. }
  212. /// <summary>
  213. /// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  214. /// </summary>
  215. /// <param name="sender"></param>
  216. /// <param name="e"></param>
  217. private void Connect_Load_1(object sender, EventArgs e)
  218. {
  219. //create a new NetworkBrowser object, and get the
  220. //list of network computers it found, and add each
  221. //entry to the combo box on this form
  222.  
  223. try
  224. {
  225. NetworkBrowser nb = new NetworkBrowser();
  226. foreach (string pc in nb.getNetworkComputers())
  227. {
  228.  
  229.  
  230. // Show the IP
  231.  
  232. //MessageBox.Show(myIP);
  233. comboBox1.Items.Add(pc);
  234. }
  235. }
  236. catch (Exception ex)
  237. {
  238. MessageBox.Show("An error occurred trying to access the network computers", "error",
  239. MessageBoxButtons.OK, MessageBoxIcon.Error);
  240. //Application.Exit();
  241. }
  242.  
  243.  
  244. ///////////WaitFor connection
  245. try
  246. {
  247. //create the listening socket...
  248. m_socListener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  249. IPEndPoint ipLocal = new IPEndPoint(IPAddress.Any, 8444);
  250. //bind to local IP Address...
  251. m_socListener.Bind(ipLocal);
  252. //start listening...
  253. m_socListener.Listen(4);
  254. // create the call back for any client connections...
  255. m_socListener.BeginAccept(new AsyncCallback(OnClientConnect1), null);
  256. button8.Enabled = false;
  257.  
  258. }
  259. catch (SocketException se)
  260. {
  261. MessageBox.Show(se.Message);
  262. }
  263.  
  264.  
  265.  
  266. /////Wait File transfer
  267. try
  268. {
  269. if (FTServerCode.receivedPath.Length > 0)
  270. backgroundWorker1.RunWorkerAsync();
  271. else
  272. MessageBox.Show("Please select file receiving path");
  273. }
  274. catch (SocketException se)
  275. {
  276. MessageBox.Show("Connection Error");
  277. }
  278.  
  279.  
  280. }
  281. /// <summary>
  282. /// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  283. /// </summary>
  284. /// <param name="sender"></param>
  285. /// <param name="e"></param>
  286. private void button3_Click(object sender, EventArgs e)
  287. {
  288. //HOME frm = new HOME();
  289. //frm.Show();
  290. if (m_socClient != null)
  291. {
  292. //m_socClient.Shutdown (SocketShutdown.Send);
  293. m_socClient.Close();
  294. m_socClient = null;
  295. //EnableCommands(true);
  296. }
  297. }
  298.  
  299.  
  300.  
  301. /// <summary>
  302. /// //////////////////////////////////////////////////////////////////////////////////////////////////////////////
  303. /// </summary>
  304. /// <param name="sender"></param>
  305. /// <param name="e"></param>
  306. public void WaitForData()
  307. {
  308. try
  309. {
  310. if (pfnCallBack == null)
  311. {
  312. pfnCallBack = new AsyncCallback(OnDataReceived);
  313. }
  314. CSocketPacket theSocPkt = new CSocketPacket();
  315. theSocPkt.thisSocket = m_socClient;
  316. // now start to listen for any data...
  317. m_asynResult = m_socClient.BeginReceive(theSocPkt.dataBuffer, 0, theSocPkt.dataBuffer.Length, SocketFlags.None, pfnCallBack, theSocPkt);
  318. }
  319. catch (SocketException se)
  320. {
  321. MessageBox.Show(se.Message);
  322. }
  323.  
  324. }
  325.  
  326. public void OnDataReceived(IAsyncResult asyn)
  327. {
  328. try
  329. {
  330. CSocketPacket theSockId = (CSocketPacket)asyn.AsyncState;
  331. //end receive...
  332. int iRx = 0;
  333. iRx = theSockId.thisSocket.EndReceive(asyn);
  334. char[] chars = new char[iRx + 1];
  335. System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder();
  336. int charLen = d.GetChars(theSockId.dataBuffer, 0, iRx, chars, 0);
  337. System.String szData = new System.String(chars);
  338. textBox1.Text =textBox1.Text + "\r\nFag04-> "+szData+"\r\n";
  339. WaitForData();
  340. }
  341. catch (ObjectDisposedException)
  342. {
  343. System.Diagnostics.Debugger.Log(0, "1", "\nOnDataReceived: Socket has been closed\n");
  344. }
  345. catch (SocketException se)
  346. {
  347. MessageBox.Show(se.Message);
  348. }
  349. }
  350. /*private void cmdListen_Click(object sender, System.EventArgs e)
  351. {
  352. try
  353. {
  354. //create the listening socket...
  355. m_socListener = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
  356. IPEndPoint ipLocal = new IPEndPoint ( IPAddress.Any ,8221);
  357. //bind to local IP Address...
  358. m_socListener.Bind( ipLocal );
  359. //start listening...
  360. m_socListener.Listen (4);
  361. // create the call back for any client connections...
  362. m_socListener.BeginAccept(new AsyncCallback( OnClientConnect ),null);
  363. cmdListen.Enabled = false;
  364.  
  365. }
  366. catch(SocketException se)
  367. {
  368. MessageBox.Show ( se.Message );
  369. }
  370. }*/
  371.  
  372.  
  373. /* private void button8_Click(object sender, EventArgs e)
  374.   {
  375.   try
  376.   {
  377.   //create the listening socket...
  378.   m_socListener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  379.   IPEndPoint ipLocal = new IPEndPoint(IPAddress.Any, 8444);
  380.   //bind to local IP Address...
  381.   m_socListener.Bind(ipLocal);
  382.   //start listening...
  383.   m_socListener.Listen(4);
  384.   // create the call back for any client connections...
  385.   m_socListener.BeginAccept(new AsyncCallback(OnClientConnect1), null);
  386.   button8.Enabled = false;
  387.  
  388.   }
  389.   catch (SocketException se)
  390.   {
  391.   MessageBox.Show(se.Message);
  392.   }
  393.   }
  394.   */
  395. private void button2_Click_1(object sender, EventArgs e)
  396. {
  397. try
  398. {
  399. Object objData = txtDataTx.Text;
  400. txtDataRx.Text = txtDataRx.Text + "ME-> " + txtDataTx.TabIndex + "\r\n";
  401. txtDataTx.Text = "";
  402. byte[] byData = System.Text.Encoding.ASCII.GetBytes(objData.ToString());
  403. m_socWorker.Send(byData);
  404. }
  405. catch (SocketException se)
  406. {
  407. MessageBox.Show(se.Message);
  408. }
  409. }
  410.  
  411.  
  412.  
  413.  
  414.  
  415.  
  416. /* private void button2_Click_1(object sender, EventArgs e)
  417.   {
  418.   try
  419.   {
  420.   Object objData = txtDataTx.Text;
  421.   byte[] byData = System.Text.Encoding.ASCII.GetBytes(objData.ToString());
  422.   m_socWorker.Send(byData);
  423.   }
  424.   catch (SocketException se)
  425.   {
  426.   MessageBox.Show(se.Message);
  427.   }
  428.   }
  429.  
  430.   */
  431. //server
  432. public void OnClientConnect1(IAsyncResult asyn)
  433. {
  434. try
  435. {
  436. m_socWorker = m_socListener.EndAccept(asyn);
  437.  
  438. WaitForData1(m_socWorker);
  439. }
  440. catch (ObjectDisposedException)
  441. {
  442. System.Diagnostics.Debugger.Log(0, "1", "\n OnClientConnection: Socket has been closed\n");
  443. }
  444. catch (SocketException se)
  445. {
  446. MessageBox.Show(se.Message);
  447. }
  448.  
  449. }
  450. public class CSocketPacket1
  451. {
  452. public System.Net.Sockets.Socket thisSocket;
  453. public byte[] dataBuffer = new byte[1];
  454. }
  455.  
  456. public void WaitForData1(System.Net.Sockets.Socket soc)
  457. {
  458. try
  459. {
  460. if (pfnWorkerCallBack == null)
  461. {
  462. pfnWorkerCallBack = new AsyncCallback(OnDataReceived1);
  463. }
  464. CSocketPacket1 theSocPkt = new CSocketPacket1();
  465. theSocPkt.thisSocket = soc;
  466. // now start to listen for any data...
  467. soc.BeginReceive(theSocPkt.dataBuffer, 0, theSocPkt.dataBuffer.Length, SocketFlags.None, pfnWorkerCallBack, theSocPkt);
  468. }
  469. catch (SocketException se)
  470. {
  471. MessageBox.Show(se.Message);
  472. }
  473.  
  474. }
  475.  
  476. public void OnDataReceived1(IAsyncResult asyn)
  477. {
  478. try
  479. {
  480. CSocketPacket1 theSockId = (CSocketPacket1)asyn.AsyncState;
  481. //end receive...
  482. int iRx = 0;
  483. iRx = theSockId.thisSocket.EndReceive(asyn);
  484. char[] chars = new char[iRx + 1];
  485. System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder();
  486. int charLen = d.GetChars(theSockId.dataBuffer, 0, iRx, chars, 0);
  487. System.String szData = new System.String(chars);
  488. textBox1.Text = textBox1.Text + szData;
  489. WaitForData1(m_socWorker);
  490. }
  491. catch (ObjectDisposedException)
  492. {
  493. System.Diagnostics.Debugger.Log(0, "1", "\nOnDataReceived: Socket has been closed\n");
  494. }
  495. catch (SocketException se)
  496. {
  497. MessageBox.Show(se.Message);
  498. }
  499. }
  500. /// <summary>
  501. /// File Transfer Server
  502. /// </summary>
  503.  
  504. /*private void button9_Click(object sender, EventArgs e)
  505.   {
  506.   FolderBrowserDialog fd = new FolderBrowserDialog();
  507.   if (fd.ShowDialog() == DialogResult.OK)
  508.   {
  509.   FTServerCode.receivedPath = fd.SelectedPath;
  510.   }
  511.   }*/
  512.  
  513. /*private void button10_Click(object sender, EventArgs e)
  514.   {
  515.   if (FTServerCode.receivedPath.Length > 0)
  516.   backgroundWorker1.RunWorkerAsync();
  517.   else
  518.   MessageBox.Show("Please select file receiving path");
  519.   }*/
  520. private void timer1_Tick(object sender, EventArgs e)
  521. {
  522. label5.Text = FTServerCode.receivedPath;
  523. label3.Text = FTServerCode.curMsg;
  524. }
  525.  
  526. FTServerCode obj = new FTServerCode();
  527. private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
  528. {
  529.  
  530. obj.StartServer();
  531. }
  532. private void button11_Click(object sender, EventArgs e)
  533. {
  534. FileDialog fDg = new OpenFileDialog();
  535. if (fDg.ShowDialog() == DialogResult.OK)
  536. {
  537. FTClientCode.SendFile(fDg.FileName,client_ip);
  538. }
  539. }
  540.  
  541. private void recievingPathToolStripMenuItem_Click(object sender, EventArgs e)
  542. {
  543. FolderBrowserDialog fd = new FolderBrowserDialog();
  544. if (fd.ShowDialog() == DialogResult.OK)
  545. {
  546. FTServerCode.receivedPath = fd.SelectedPath;
  547. backgroundWorker1.RunWorkerAsync();
  548. }
  549. }
  550.  
  551. private void button10_Click(object sender, EventArgs e)
  552. {
  553. try
  554. {
  555. if (FTServerCode.receivedPath.Length > 0)
  556. backgroundWorker1.RunWorkerAsync();
  557. else
  558. MessageBox.Show("Please select file receiving path");
  559. }
  560. catch (SocketException se)
  561. {
  562. MessageBox.Show("Connection Error");
  563. }
  564.  
  565. }
  566.  
  567. private void button9_Click(object sender, EventArgs e)
  568. {
  569. FolderBrowserDialog fd = new FolderBrowserDialog();
  570. if (fd.ShowDialog() == DialogResult.OK)
  571. {
  572. FTServerCode.receivedPath = fd.SelectedPath;
  573. backgroundWorker1.RunWorkerAsync();
  574. }
  575. }
  576.  
  577.  
  578. }
  579.  
  580. class FTServerCode
  581. {
  582. IPEndPoint ipEnd;
  583. Socket sock;
  584. public FTServerCode()
  585. {
  586. ipEnd = new IPEndPoint(IPAddress.Any, 5656);
  587. sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
  588. sock.Bind(ipEnd);
  589. }
  590. public static string receivedPath;
  591. public static string curMsg = "Stopped";
  592. public void StartServer()
  593. {
  594. try
  595. {
  596. curMsg = "Starting...";
  597. sock.Listen(100);
  598.  
  599. curMsg = "Running and waiting to receive file.";
  600. Socket clientSock = sock.Accept();
  601.  
  602. byte[] clientData = new byte[1024 * 5000];
  603.  
  604. int receivedBytesLen = clientSock.Receive(clientData);
  605. curMsg = "Receiving data...";
  606.  
  607. int fileNameLen = BitConverter.ToInt32(clientData, 0);
  608. string fileName = Encoding.ASCII.GetString(clientData, 4, fileNameLen);
  609.  
  610. BinaryWriter bWrite = new BinaryWriter(File.Open(receivedPath + "/" + fileName, FileMode.Append)); ;
  611. bWrite.Write(clientData, 4 + fileNameLen, receivedBytesLen - 4 - fileNameLen);
  612.  
  613. curMsg = "Saving file...";
  614.  
  615. bWrite.Close();
  616. clientSock.Close();
  617. curMsg = "Reeived & Saved file; Server Stopped.";
  618. }
  619. catch (Exception ex)
  620. {
  621. curMsg = "File Receving error.";
  622. }
  623. }
  624. }
  625.  
  626.  
  627. /// <summary>
  628. /// File Transfer Client
  629. /// </summary>
  630. class FTClientCode
  631. {
  632. public static string curMsg = "Idle";
  633. public static void SendFile(string fileName,string dest_ip)
  634. {
  635. try
  636. {
  637. string myIP = System.Net.Dns.GetHostByName(dest_ip).AddressList[0].ToString();
  638. IPAddress ip = IPAddress.Parse(myIP);
  639. //IPAddress[] ipAddress = Dns.GetHostAddresses("localhost");
  640. IPEndPoint ipEnd = new IPEndPoint(ip.Address, 5656);
  641. Socket clientSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
  642.  
  643.  
  644. string filePath = "";
  645.  
  646. fileName = fileName.Replace("\\", "/");
  647. while (fileName.IndexOf("/") > -1)
  648. {
  649. filePath += fileName.Substring(0, fileName.IndexOf("/") + 1);
  650. fileName = fileName.Substring(fileName.IndexOf("/") + 1);
  651. }
  652.  
  653.  
  654. byte[] fileNameByte = Encoding.ASCII.GetBytes(fileName);
  655. if (fileNameByte.Length > 850 * 1024)
  656. {
  657. curMsg = "File size is more than 850kb, please try with small file.";
  658. return;
  659. }
  660.  
  661. curMsg = "Buffering ...";
  662. byte[] fileData = File.ReadAllBytes(filePath + fileName);
  663. byte[] clientData = new byte[4 + fileNameByte.Length + fileData.Length];
  664. byte[] fileNameLen = BitConverter.GetBytes(fileNameByte.Length);
  665.  
  666. fileNameLen.CopyTo(clientData, 0);
  667. fileNameByte.CopyTo(clientData, 4);
  668. fileData.CopyTo(clientData, 4 + fileNameByte.Length);
  669.  
  670. curMsg = "Connection to server ...";
  671. clientSock.Connect(ipEnd);
  672.  
  673. curMsg = "File sending...";
  674. clientSock.Send(clientData);
  675.  
  676. curMsg = "Disconnecting...";
  677. clientSock.Close();
  678. curMsg = "File transferred.";
  679.  
  680. }
  681. catch (Exception ex)
  682. {
  683. if (ex.Message == "No connection could be made because the target machine actively refused it")
  684. curMsg = "File Sending fail. Because server not running.";
  685. else
  686. curMsg = "File Sending fail." + ex.Message;
  687. }
  688.  
  689. }
  690. }
  691.  
  692. }
Reply With Quote Quick reply to this message  
Join Date: Mar 2008
Posts: 330
Reputation: Diamonddrake is a jewel in the rough Diamonddrake is a jewel in the rough Diamonddrake is a jewel in the rough 
Solved Threads: 39
Diamonddrake's Avatar
Diamonddrake Diamonddrake is offline Offline
Posting Whiz
 
0
  #4
26 Days Ago
I'm not sure what's causing the error you are receiving. But it looks like you are trying to send the length of the data, the Filename, and the data itself as one object. then trying to pull out the data before you are sure that you have actually received that information.

a good idea would be to first send the length of the file and the filename and then wait for the server to send a message saying its ready to receive the file, then the send the file data. and on the receiving end use a loop that keeps loading data til the read data matches the length sent.

But I am sure sknake is just going to post you a fixed version when he has time anyway. But if you are looking to do it yourself, it helps to start simple, then build on it. That's how I did it. Started with 2 console applications a client and a server, set them up to send and string messages back and fourth the added special commands to send files, then added progress indication, and eventually turned it into a forms application.
Reply With Quote Quick reply to this message  
Join Date: Oct 2009
Posts: 22
Reputation: bk_bhupendra is an unknown quantity at this point 
Solved Threads: 1
bk_bhupendra bk_bhupendra is offline Offline
Newbie Poster

socket exception

 
0
  #5
26 Days Ago
hi,
the code i have shown is working in case of two clients. There is no server. The main problem is about socket opening and closing, I think.

In this application i generate buttons corresponding to each system on my LAN from HOME page, ie Connect page is opened for all such systems...
there occurs the error. i cant open a new Connect form if i have once opened it. I tried by closing the Connect form, also closing each socket.
but still the problem remain till the whole application is stopped.
so i have to close whole application whenever i want to connect with another system, which i dnt want.

is there any connection between ports and the exception i am receiving ...
Reply With Quote Quick reply to this message  
Join Date: Feb 2009
Posts: 3,252
Reputation: sknake has much to be proud of sknake has much to be proud of sknake has much to be proud of sknake has much to be proud of sknake has much to be proud of sknake has much to be proud of sknake has much to be proud of sknake has much to be proud of sknake has much to be proud of sknake has much to be proud of 
Solved Threads: 579
Sponsor
sknake's Avatar
sknake sknake is online now Online
.NET Enthusiast
 
0
  #6
26 Days Ago
I don't think your posts were complete. Can you upload the project? The reason I say this is:
  1. AsyncClient.HOME.field_Click(Object sender, EventArgs e) in F:\BK1\projects asp\Lan Chatting sockets\Async_client\HOME.cs:line 138

According to the code you pasted HOME.CS is not 138 lines and does not contain a field_Click() method.

Here is what is causing your problem:
  1. ipEnd = new IPEndPoint(IPAddress.Any, 5656);
  2. sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
  3. sock.Bind(ipEnd);

The problem is you can only have one instance of one application listening on one port. Your code will fail if someone else already has opened that port for listening, or if you attempt to listen on the same port twice. This is the exception message you received. You should probably explain what you're attempting to do in your project (after you upload it) so we can determine how to solve it.
Scott Knake
Custom Software Development
Apex Software, Inc.
Reply With Quote Quick reply to this message  
Reply

Tags
socket

Message:


Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC