Visual C# Developer Center >
Visual C# Forums
>
Visual C# General
>
Socket communication does not transmit full string
Socket communication does not transmit full string
- I am using the code below to read a (quite lengthy) string of data separated by newlines sent from a mobile phone via a TCP socket. I am never able to receive the full string. I have never overrun the buffer. Any advice?
public class aClass
{ Socket mainSocket; List<Socket> socketList; int port = 8000; public aClass() { mainSocket = new Socket(AddressFamily.Unspecified, SocketType.Stream, ProtocolType.Tcp); IPEndPoint local = new IPEndPoint(IPAddress.Any, port); socketList = new List<Socket>(); mainSocket.Bind(local); mainSocket.Listen(4); mainSocket.BeginAccept(new AsyncCallback(endConnect), null); } private void endConnect(IAsyncResult ar) { Socket newSocket = mainSocket.EndAccept(ar); beginListen(newSocket); socketList.Add(newSocket); } // Class obtained from Jayan Nair public class SocketPacket { public System.Net.Sockets.Socket m_currentSocket; public byte[] dataBuffer = new byte[2048]; } private void beginListen(Socket theSocket) { SocketPacket sp = new SocketPacket(); sp.m_currentSocket = theSocket; theSocket.BeginReceive(sp.dataBuffer, 0, sp.dataBuffer.Length, SocketFlags.None, new AsyncCallback(onReceive), sp); } private void onReceive(IAsyncResult ar) { SocketPacket socketData = (SocketPacket)ar.AsyncState; Socket theSocket = socketData.m_currentSocket; int nBytes = theSocket.EndReceive(ar); if (nBytes > 0) { String dataStr = Encoding.ASCII.GetString(socketData.dataBuffer, 2, nBytes); if (dataStr.Contains("over")) { disconnect(theSocket); } else { parse(dataStr); beginListen(theSocket); } } } private void disconnect (Socket theSocket) { // To be written } }
Answers
- You need message framing: http://nitoprograms.blogspot.com/2009/04/message-framing.html
-Steve
Programming blog: http://nitoprograms.blogspot.com/
Including my TCP/IP .NET Sockets FAQ
Microsoft Certified Professional Developer- Marked As Answer byHarry ZhuMSFT, ModeratorTuesday, November 10, 2009 4:36 AM
All Replies
- You need message framing: http://nitoprograms.blogspot.com/2009/04/message-framing.html
-Steve
Programming blog: http://nitoprograms.blogspot.com/
Including my TCP/IP .NET Sockets FAQ
Microsoft Certified Professional Developer- Marked As Answer byHarry ZhuMSFT, ModeratorTuesday, November 10, 2009 4:36 AM


