Search Results

Search found 108 results on 5 pages for 'tcpclient'.

Page 1/5 | 1 2 3 4 5  | Next Page >

  • Is TcpClient BeginRead/Send thread safe?

    - by wb
    Using a dotNET TcpClient if I have called an asynchronous BeginRead() on the associated network stream can I still call Write() on that stream on another thread? Or do I have to lock() the TcpClient in the code that is called back from the BeginRead and the code that does the send? Also if I close the TcpClient with: client.GetStream().Close(); client.Close(); Do I have to lock() on the TcpClient as well? Thanks in advance.

    Read the article

  • C# TcpClient, getting back the entire response from a telnet device

    - by Dan Bailiff
    I'm writing a configuration tool for a device that can communicate via telnet. The tool sends a command via TcpClient.GetStream().Write(...), and then checks for the device response via TcpClient.GetStream().ReadByte(). This works fine in unit tests or when I'm stepping through code slowly. If I run the config tool such that it performs multiple commands consecutively, then the behavior of the read is inconsistent. By inconsistent I mean sometimes the data is missing, incomplete or partially garbled. So even though the device performed the operation and responded, my code to check for the response was unreliable. I "fixed" this problem by adding a Thread.Sleep to make sure the read method waits long enough for the device to complete its job and send back the whole response (in this case 1.5 seconds was a safe amount). I feel like this is wrong, blocking everything for a fixed time, and I wonder if there is a better way to get the read method to wait only long enough to get the whole response from the device. private string Read() { if (!tcpClient.Connected) throw (new Exception("Read() failed: Telnet connection not available.")); StringBuilder sb = new StringBuilder(); do { ParseTelnet(ref sb); System.Threading.Thread.Sleep(1500); } while (tcpClient.Available > 0); return sb.ToString(); } private void ParseTelnet(ref StringBuilder sb) { while (tcpClient.Available > 0) { int input = tcpClient.GetStream().ReadByte(); switch (input) { // parse the input // ... do other things in special cases default: sb.Append((char)input); break; } } }

    Read the article

  • How to check if TcpClient Connection is closed?

    - by Superdumbell
    I'm playing around with the TcpClient and I'm trying to figure out how to make the Connected property say false when a connection is dropped. I tried doing NetworkStream ns = client.GetStream(); ns.Write(new byte[1], 0, 0); But it still will not show me if the TcpClient is disconnected. How would you go about this using a TcpClient?

    Read the article

  • How much buffer does NetworkStream and TcpClient have?

    - by Earlz
    Hello, We are writing a TCPServer and Client program. How much space is there in the TcpClient buffer? Like, at what point will it begin to throw away data? We are trying to determine if the TcpClient can be blocking or if it should go into it's own background thread(so that the buffer can not get full)..

    Read the article

  • Jumbled byte array after using TcpClient and TcpListener

    - by Dylan
    I want to use the TcpClient and TcpListener to send an mp3 file over a network. I implemented a solution of this using sockets, but there were some issues so I am investigating a new/better way to send a file. I create a byte array which looks like this: length_of_filename|filename|file This should then be transmitted using the above mentioned classes, yet on the server side the byte array I read is completely messed up and I'm not sure why. The method I use to send: public static void Send(String filePath) { try { IPEndPoint endPoint = new IPEndPoint(Settings.IpAddress, Settings.Port + 1); Byte[] fileData = File.ReadAllBytes(filePath); FileInfo fi = new FileInfo(filePath); List<byte> dataToSend = new List<byte>(); dataToSend.AddRange(BitConverter.GetBytes(Encoding.Unicode.GetByteCount(fi.Name))); // length of filename dataToSend.AddRange(Encoding.Unicode.GetBytes(fi.Name)); // filename dataToSend.AddRange(fileData); // file binary data using (TcpClient client = new TcpClient()) { client.Connect(Settings.IpAddress, Settings.Port + 1); // Get a client stream for reading and writing. using (NetworkStream stream = client.GetStream()) { // server is ready stream.Write(dataToSend.ToArray(), 0, dataToSend.ToArray().Length); } } } catch (ArgumentNullException e) { Debug.WriteLine(e); } catch (SocketException e) { Debug.WriteLine(e); } } } Then on the server side it looks as follows: private void Listen() { TcpListener server = null; try { // Setup the TcpListener Int32 port = Settings.Port + 1; IPAddress localAddr = IPAddress.Parse("127.0.0.1"); // TcpListener server = new TcpListener(port); server = new TcpListener(localAddr, port); // Start listening for client requests. server.Start(); // Buffer for reading data Byte[] bytes = new Byte[1024]; List<byte> data; // Enter the listening loop. while (true) { Debug.WriteLine("Waiting for a connection... "); string filePath = string.Empty; // Perform a blocking call to accept requests. // You could also user server.AcceptSocket() here. using (TcpClient client = server.AcceptTcpClient()) { Debug.WriteLine("Connected to client!"); data = new List<byte>(); // Get a stream object for reading and writing using (NetworkStream stream = client.GetStream()) { // Loop to receive all the data sent by the client. while ((stream.Read(bytes, 0, bytes.Length)) != 0) { data.AddRange(bytes); } } } int fileNameLength = BitConverter.ToInt32(data.ToArray(), 0); filePath = Encoding.Unicode.GetString(data.ToArray(), 4, fileNameLength); var binary = data.GetRange(4 + fileNameLength, data.Count - 4 - fileNameLength); Debug.WriteLine("File successfully downloaded!"); // write it to disk using (BinaryWriter writer = new BinaryWriter(File.Open(filePath, FileMode.Append))) { writer.Write(binary.ToArray(), 0, binary.Count); } } } catch (Exception ex) { Debug.WriteLine(ex); } finally { // Stop listening for new clients. server.Stop(); } } Can anyone see something that I am missing/doing wrong?

    Read the article

  • HttpTunneling a TCPClient application

    - by user360116
    We have a custom chat application(c#) which uses TCPClient. We are having problem on clients who are behind Firewall or proxy. We know that these client can browse the internet without a problem so we decided to change our TCPClient application so that It uses HTTP messages to communicate. Will it be enough just to wrap our text massages with standard HTML tags and HTTP headers? We need a long lasting connection. Does keep-alive have a limit? Do firewalls or proxies have time limits for "alive" connections.

    Read the article

  • How do i judge when the NetWorkStream finishes by using .net TcpClient to communicate

    - by Hwasin
    I try to use stream.DataAvailable to judge if it is finished,but sometimes the value is false but after a little while it is true again,i have to set a counter and judge the end by the symbol '' like this int connectCounter = 0; while (connectCounter < 1200) { if (stream.DataAvailable) { while (stream.DataAvailable) { byte[] buffer = new byte[bufferSize]; int flag = stream.Read(buffer, 0, buffer.Length); string strReadXML_t = System.Text.Encoding.Default.GetString(buffer); strReadXML = strReadXML + strReadXML_t.Replace("\0", string.Empty); } if (strReadXML.Substring(strReadXML.Length - 1, 1).Equals(">")) { break; } } Thread.Sleep(100); connectCounter++; } is there any good methord to deal with it?Thank you!

    Read the article

  • There's a black hole in my server (TcpClient, TcpListener)

    - by Matías
    Hi, I'm trying to build a server that will receive files sent by clients over a network. If the client decides to send one file at a time, there's no problem, I get the file as I expected, but if it tries to send more than one I only get the first one. Here's the server code: I'm using one Thread per connected client public void ProcessClients() { while (IsListening) { ClientHandler clientHandler = new ClientHandler(listener.AcceptTcpClient()); Thread thread = new Thread(new ThreadStart(clientHandler.Process)); thread.Start(); } } The following code is part of ClientHandler class public void Process() { while (client.Connected) { using (MemoryStream memStream = new MemoryStream()) { int read; while ((read = client.GetStream().Read(buffer, 0, buffer.Length)) > 0) { memStream.Write(buffer, 0, read); } if (memStream.Length > 0) { Packet receivedPacket = (Packet)Tools.Deserialize(memStream.ToArray()); File.WriteAllBytes(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), Guid.NewGuid() + receivedPacket.Filename), receivedPacket.Content); } } } } On the first iteration I get the first file sent, but after it I don't get anything. I've tried using a Thread.Sleep(1000) at the end of every iteration without any luck. On the other side I have this code (for clients) . . client.Connect(); foreach (var oneFilename in fileList) client.Upload(oneFilename); client.Disconnect(); . . The method Upload: public void Upload(string filename) { FileInfo fileInfo = new FileInfo(filename); Packet packet = new Packet() { Filename = fileInfo.Name, Content = File.ReadAllBytes(filename) }; byte[] serializedPacket = Tools.Serialize(packet); netStream.Write(serializedPacket, 0, serializedPacket.Length); netStream.Flush(); } netStream (NetworkStream) is opened on Connect method, and closed on Disconnect. Where's the black hole? Can I send multiple objects as I'm trying to do? Thanks for your time.

    Read the article

  • Should TcpClient be used for this scenario?

    - by Martín Marconcini
    I have to communicate with an iPhone. I have its IP Address and the port (obtained via Bonjour). I need to send a header that is “0x50544833” (or similar, It’s an HEX number), then the size of the data (below) and then the data itself. The data is just a string that looks like this: <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE plist SYSTEM "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>clientName</key> <string>XXX</string> <key>clientService</key> <string>0be397e7-21f4-4d3c-89d0-cdf179a7e14d</string> <key>registerCode</key> <string>0000</string> </dict> </plist> The requirement also says that I must send the data in little endian format (which I think is the default for Intel anyway). So it would be: hex_number + size of data + string_with_the_above_xml. I need to send that to the iPhone and read the response. What would be, according to your experience, the best way to send this data (and read the response)?

    Read the article

  • send multiple file over TCP with C# using TcpClient

    - by xnoor
    I'm trying to send multiple files over TCP using C# TcpClient, for a single file it works great, but when I have multiple files, it sends only the first one. Here is my code: SENDING FILES try { TcpClient tcpClient = new TcpClient(); NetworkStream networkStream; FileStream fileStream = null; tcpClient.Connect(appUpdateMessage.receiverIpAddress, 12000); networkStream = tcpClient.GetStream(); byte[] byteSend = new byte[tcpClient.ReceiveBufferSize]; string startupPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase).Substring(6); DirectoryInfo directoriesInfo = new DirectoryInfo(startupPath); DirectoryInfo[] directories = directoriesInfo.GetDirectories(); FileInfo[] files = directoriesInfo.GetFiles(); for (int iLoop = 0; iLoop < directories.Length; iLoop++) { FileInfo[] subdirectoryFiles = directories[iLoop].GetFiles(); foreach (FileInfo fi in subdirectoryFiles) { fileStream = new FileStream(fi.FullName, FileMode.Open, FileAccess.Read); BinaryReader binFile = new BinaryReader(fileStream); FileUpdateMessage fileUpdateMessage = new FileUpdateMessage(); fileUpdateMessage.fileName = fi.Name; fileUpdateMessage.fileSize = fi.Length; fileUpdateMessage.targetDirectory = fi.Directory.Name; MessageContainer messageContainer = new MessageContainer(); messageContainer.messageType = MessageType.FileProperties; messageContainer.messageContnet = SerializationManager.XmlFormatterObjectToByteArray(fileUpdateMessage); byte[] messageByte = SerializationManager.XmlFormatterObjectToByteArray(messageContainer); networkStream.Write(messageByte, 0, messageByte.Length); int bytesSize = 0; byte[] downBuffer = new byte[2048]; while ((bytesSize = fileStream.Read(downBuffer, 0, downBuffer.Length)) > 0) { networkStream.Write(downBuffer, 0, bytesSize); } fileStream.Close(); } } tcpClient.Close(); networkStream.Close(); return true; } catch (Exception ex) { //logger.Info(ex.Message); return false; } finally { } RECEIVING FILES try { TcpClient tcpClient = c as TcpClient; NetworkStream networkstream = tcpClient.GetStream(); FileStream fileStream = null; byte[] _data = new byte[1024]; int _bytesRead = 0; _bytesRead = networkstream.Read(_data, 0, _data.Length); MessageContainer messageContainer = new MessageContainer(); messageContainer = SerializationManager.XmlFormatterByteArrayToObject(_data, messageContainer) as MessageContainer; switch (messageContainer.messageType) { case MessageType.FileProperties: FileUpdateMessage fileUpdateMessage = new FileUpdateMessage(); fileUpdateMessage = SerializationManager.XmlFormatterByteArrayToObject(messageContainer.messageContnet, fileUpdateMessage) as FileUpdateMessage; string startupPath = @"d:updatefolder";//System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase).Substring(6); DirectoryInfo mainDirectory = new DirectoryInfo(startupPath); DirectoryInfo targetDirecotry = new DirectoryInfo(startupPath + "\\" + fileUpdateMessage.targetDirectory); if (!targetDirecotry.Exists) { mainDirectory.CreateSubdirectory(fileUpdateMessage.targetDirectory); } fileStream = new FileStream(startupPath + "\\" + fileUpdateMessage.targetDirectory + "\\" + fileUpdateMessage.fileName, FileMode.Create, FileAccess.Write, FileShare.ReadWrite); long filezie = fileUpdateMessage.fileSize; int byteSize = 0; byte[] downBuffer = new byte[2048]; while ((byteSize = networkstream.Read(downBuffer, 0, downBuffer.Length)) > 0) { fileStream.Write(downBuffer, 0, byteSize); if (this.InvokeRequired) { this.Invoke((MethodInvoker)delegate { //progressBar1.Value = Convert.ToInt32((byteSize * 100) / fileUpdateMessage.fileSize); progressBar1.Value = Convert.ToInt32((fileStream.Length * 100) / fileUpdateMessage.fileSize); lblFileName.Text = fileUpdateMessage.fileName; }); } else { //progressBar1.Value = Convert.ToInt32((byteSize * 100) / fileUpdateMessage.fileSize); lblFileName.Text = fileUpdateMessage.fileName; } } fileStream.Close(); networkstream.Close(); break; } } catch (Exception ex) { //logger.Error(ex.Message); } Any idea what I am doing wrong?

    Read the article

  • How do I get client ip address using TcpClient?

    - by brendan
    I am using TcpClient to listen on a port for requests. When the requests come in from the client I want to know the client ip making the request. I've tried: Console.WriteLine(tcpClient.Client.RemoteEndPoint.ToString()); Console.WriteLine(tcpClient.Client.LocalEndPoint.ToString()); var networkStream = tcpClient.GetStream(); var pi = networkStream.GetType().GetProperty("Socket", BindingFlags.NonPublic | BindingFlags.Instance); var socketIp = ((Socket)pi.GetValue(networkStream, null)).RemoteEndPoint.ToString(); Console.WriteLine(socketIp); All of these addresses output 10.x.x.x addresses which are private addresses and are clearly not the address of the clients off my network making the requests. What can I do to get the public ip of the clients making the requests?

    Read the article

  • Do I have to store a TcpClient even though I only care about its stream?

    - by mafutrct
    A new instance of a TcpClient connects to a remote host. Its NetworkStream is retrieved and stored. Do I have to store the TcpClient itself as well to make sure it is not garbage collected? In case you're going to answer "You have to store it to be able to dispose it": In my specific case, the TcpClient is usually living for a long time (app lifetime), so disposing it is not really a must. However, I agree that, in general, it has to be stored just to be able to call Dispose.

    Read the article

  • TCPClient in C# (Error).

    - by CSharp
    using System; using System.Text; using System.IO; using System.Net.Sockets; namespace ConsoleApp01 { class Program { public static void Main(string[] args) { TcpClient client = new TcpClient("python.org",80); NetworkStream ns = client.GetStream(); StreamWriter sw = new StreamWriter(ns); sw.Write("HEAD / HTTP/1.1\r\n" + "User-Agent: Test\r\n" + "Host: www.python.org\r\n" + "Connection: Close\r\n"); sw.Flush(); Console.ReadKey(true); } } } System.Net.Sockets.SocketException: Unable to make a connection because the target machine actively refused it at System.Net.Sockets.TcpClient..ctor at ConsoleApp01.Program.Main :line 12 Why do i get this error message?

    Read the article

  • Reading a POP3 server with only TcpClient and StreamWriter/StreamReader[SOLVED]

    - by WebDevHobo
    I'm trying to read mails from my live.com account, via the POP3 protocol. I've found the the server is pop3.live.com and the port if 995. I'm not planning on using a pre-made library, I'm using NetworkStream and StreamReader/StreamWriter for the job. I need to figure this out. So, any of the answers given here: http://stackoverflow.com/questions/44383/reading-email-using-pop3-in-c are not usefull. It's part of a larger program, but I made a small test to see if it works. Eitherway, i'm not getting anything. Here's the code I'm using, which I think should be correct. EDIT: this code is old, please refer to the second block problem solved. public Program() { string temp = ""; using(TcpClient tc = new TcpClient(new IPEndPoint(IPAddress.Parse("127.0.0.1"),8000))) { tc.Connect("pop3.live.com",995); using(NetworkStream nws = tc.GetStream()) { using(StreamReader sr = new StreamReader(nws)) { using(StreamWriter sw = new StreamWriter(nws)) { sw.WriteLine("USER " + user); sw.Flush(); sw.WriteLine("PASS " + pass); sw.Flush(); sw.WriteLine("LIST"); sw.Flush(); while(temp != ".") { temp += sr.ReadLine(); } } } } } Console.WriteLine(temp); } Visual Studio debugger constantly falls over tc.Connect("pop3.live.com",995); Which throws an "A socket operation was attempted to an unreachable network 65.55.172.253:995" error. So, I'm sending from port 8000 on my machine to port 995, the hotmail pop3 port. And I'm getting nothing, and I'm out of ideas. Second block: Problem was apparently that I didn't write the quit command. The Code: public Program() { string str = string.Empty; string strTemp = string.Empty; using(TcpClient tc = new TcpClient()) { tc.Connect("pop3.live.com",995); using(SslStream sl = new SslStream(tc.GetStream())) { sl.AuthenticateAsClient("pop3.live.com"); using(StreamReader sr = new StreamReader(sl)) { using(StreamWriter sw = new StreamWriter(sl)) { sw.WriteLine("USER " + user); sw.Flush(); sw.WriteLine("PASS " + pass); sw.Flush(); sw.WriteLine("LIST"); sw.Flush(); sw.WriteLine("QUIT "); sw.Flush(); while((strTemp = sr.ReadLine()) != null) { if(strTemp == "." || strTemp.IndexOf("-ERR") != -1) { break; } str += strTemp; } } } } } Console.WriteLine(str); }

    Read the article

  • TcpListener is queuing connections faster than I can clear them

    - by Matthew Brindley
    As I understand it, TcpListener will queue connections once you call Start(). Each time you call AcceptTcpClient (or BeginAcceptTcpClient), it will dequeue one item from the queue. If we load test our TcpListener app by sending 1,000 connections to it at once, the queue builds far faster than we can clear it, leading (eventually) to timeouts from the client because it didn't get a response because its connection was still in the queue. However, the server doesn't appear to be under much pressure, our app isn't consuming much CPU time and the other monitored resources on the machine aren't breaking a sweat. It feels like we're not running efficiently enough right now. We're calling BeginAcceptTcpListener and then immediately handing over to a ThreadPool thread to actually do the work, then calling BeginAcceptTcpClient again. The work involved doesn't seem to put any pressure on the machine, it's basically just a 3 second sleep followed by a dictionary lookup and then a 100 byte write to the TcpClient's stream. Here's the TcpListener code we're using: // Thread signal. private static ManualResetEvent tcpClientConnected = new ManualResetEvent(false); public void DoBeginAcceptTcpClient(TcpListener listener) { // Set the event to nonsignaled state. tcpClientConnected.Reset(); listener.BeginAcceptTcpClient( new AsyncCallback(DoAcceptTcpClientCallback), listener); // Wait for signal tcpClientConnected.WaitOne(); } public void DoAcceptTcpClientCallback(IAsyncResult ar) { // Get the listener that handles the client request, and the TcpClient TcpListener listener = (TcpListener)ar.AsyncState; TcpClient client = listener.EndAcceptTcpClient(ar); if (inProduction) ThreadPool.QueueUserWorkItem(state => HandleTcpRequest(client, serverCertificate)); // With SSL else ThreadPool.QueueUserWorkItem(state => HandleTcpRequest(client)); // Without SSL // Signal the calling thread to continue. tcpClientConnected.Set(); } public void Start() { currentHandledRequests = 0; tcpListener = new TcpListener(IPAddress.Any, 10000); try { tcpListener.Start(); while (true) DoBeginAcceptTcpClient(tcpListener); } catch (SocketException) { // The TcpListener is shutting down, exit gracefully CheckBuffer(); return; } } I'm assuming the answer will be related to using Sockets instead of TcpListener, or at least using TcpListener.AcceptSocket, but I wondered how we'd go about doing that? One idea we had was to call AcceptTcpClient and immediately Enqueue the TcpClient into one of multiple Queue<TcpClient> objects. That way, we could poll those queues on separate threads (one queue per thread), without running into monitors that might block the thread while waiting for other Dequeue operations. Each queue thread could then use ThreadPool.QueueUserWorkItem to have the work done in a ThreadPool thread and then move onto dequeuing the next TcpClient in its queue. Would you recommend this approach, or is our problem that we're using TcpListener and no amount of rapid dequeueing is going to fix that?

    Read the article

  • Reading a POP3 server with only TcpClient and StreamWriter/StreamReader

    - by WebDevHobo
    I'm trying to read mails from my live.com account, via the POP3 protocol. I've found the the server is pop3.live.com and the port if 587. I'm not planning on using a pre-made library, I'm using NetworkStream and StreamReader/StreamWriter for the job. I need to figure this out. So, any of the answers given here: http://stackoverflow.com/questions/44383/reading-email-using-pop3-in-c are not usefull. It's part of a larger program, but I made a small test to see if it works. Eitherway, i'm not getting anything. Here's the code I'm using, which I think should be correct. public Program() { string temp = ""; using(TcpClient tc = new TcpClient(new IPEndPoint(IPAddress.Parse("127.0.0.1"),8000))) { tc.Connect("pop3.live.com",587); using(NetworkStream nws = tc.GetStream()) { using(StreamReader sr = new StreamReader(nws)) { using(StreamWriter sw = new StreamWriter(nws)) { sw.WriteLine("USER " + user); sw.Flush(); sw.WriteLine("PASS " + pass); sw.Flush(); sw.WriteLine("LIST"); sw.Flush(); while(temp != ".") { temp += sr.ReadLine(); } } } } } Console.WriteLine(temp); } So, I'm sending from port 8000 on my machine to port 587, the hotmail pop3 port. And I'm getting nothing, and I'm out of ideas.

    Read the article

  • How to use Tor control protocol in C#?

    - by Ed
    I'm trying to send commands to the Tor control port programmatically to make it refresh the chain. I haven't been able to find any examples in C#, and my solution's not working. The request times out. I have the service running, and I can see it listening on the control port. public string Refresh() { TcpClient client = new TcpClient("localhost", 9051); string response = string.Empty; string authenticate = MakeTcpRequest("AUTHENTICATE", client); if (authenticate.Equals("250")) response = MakeTcpRequest("SIGNAL NEWNYM", client); client.Close(); return response; } public string MakeTcpRequest(string message, TcpClient client) { client.ReceiveTimeout = 20000; client.SendTimeout = 20000; string proxyResponse = string.Empty; try { // Send message StreamWriter streamWriter = new StreamWriter(client.GetStream()); streamWriter.Write(message); streamWriter.Flush(); // Read response StreamReader streamReader = new StreamReader(client.GetStream()); proxyResponse = streamReader.ReadToEnd(); } catch (Exception ex) { // Ignore } return proxyResponse; } Can anyone spot what I'm doing wrong?

    Read the article

  • help convert pop3 connection to imap

    - by MyHeadHurts
    tcpClient.Connect(hostName, 110) Dim networkStream As NetworkStream = tcpClient.GetStream() Dim bytes(tcpClient.ReceiveBufferSize) As Byte Dim sendBytes As Byte() networkStream.Read(bytes, 0, CInt(tcpClient.ReceiveBufferSize)) sendBytes = Encoding.ASCII.GetBytes("User " + userName + vbCrLf) networkStream.Write(sendBytes, 0, sendBytes.Length) sTemp = networkStream.Read(bytes, 0, CInt(tcpClient.ReceiveBufferSize)) sendBytes = Encoding.ASCII.GetBytes("Pass " + userPassword + vbCrLf) networkStream.Write(sendBytes, 0, sendBytes.Length) sTemp = networkStream.Read(bytes, 0, CInt(tcpClient.ReceiveBufferSize)) sendBytes = Encoding.ASCII.GetBytes("STAT" + vbCrLf) networkStream.Write(sendBytes, 0, sendBytes.Length) sTemp = networkStream.Read(bytes, 0, CInt(tcpClient.ReceiveBufferSize)) sendBytes = Encoding.ASCII.GetBytes("RETR " + messageNumber + vbCrLf) networkStream.Write(sendBytes, 0, sendBytes.Length) networkStream.Read(bytes, 0, CInt(tcpClient.ReceiveBufferSize)) returnMessage = Encoding.ASCII.GetString(bytes) EmailContent.Text = returnMessage sendBytes = Encoding.ASCII.GetBytes("QUIT" + vbCrLf) networkStream.Write(sendBytes, 0, sendBytes.Length) tcpClient.Close() Catch ex As Exception EmailContent.Text = "Could not retrieve email or your inbox is empty" End Try

    Read the article

  • connecting to exchange server

    - by MyHeadHurts
    I am using this code to connect to my exchange server. I am trying to retrieve an inbox of basically emails that have not been read however, i am just getting a bunch of gibberish and its reading an email. can you help me modify my code to just read the most recent messages. Try tcpClient.Connect(hostName, 110) Dim networkStream As NetworkStream = tcpClient.GetStream() Dim bytes(tcpClient.ReceiveBufferSize) As Byte Dim sendBytes As Byte() networkStream.Read(bytes, 0, CInt(tcpClient.ReceiveBufferSize)) sendBytes = Encoding.ASCII.GetBytes("User " + userName + vbCrLf) networkStream.Write(sendBytes, 0, sendBytes.Length) sTemp = networkStream.Read(bytes, 0, CInt(tcpClient.ReceiveBufferSize)) sendBytes = Encoding.ASCII.GetBytes("Pass " + userPassword + vbCrLf) networkStream.Write(sendBytes, 0, sendBytes.Length) sTemp = networkStream.Read(bytes, 0, CInt(tcpClient.ReceiveBufferSize)) sendBytes = Encoding.ASCII.GetBytes("STAT" + vbCrLf) networkStream.Write(sendBytes, 0, sendBytes.Length) sTemp = networkStream.Read(bytes, 0, CInt(tcpClient.ReceiveBufferSize)) sendBytes = Encoding.ASCII.GetBytes("RETR " + messageNumber + vbCrLf) networkStream.Write(sendBytes, 0, sendBytes.Length) networkStream.Read(bytes, 0, CInt(tcpClient.ReceiveBufferSize)) returnMessage = Encoding.ASCII.GetString(bytes) EmailContent.Text = returnMessage sendBytes = Encoding.ASCII.GetBytes("QUIT" + vbCrLf) networkStream.Write(sendBytes, 0, sendBytes.Length) tcpClient.Close() Catch ex As Exception EmailContent.Text = "Could not retrieve email or your inbox is empty" End Try

    Read the article

  • Ruby background service

    - by FancyDancy
    I have a TCPclient written on Ruby. I want to use it in background. Currently it has a loop: loop do end So i can run a client, and it works forever. Is there a way to run in as a service, and write a pid to file, then i'll able to kill that process by pid?

    Read the article

  • Searching for patterns to create a TCP Connection Pool for high performance messaging

    - by JoeGeeky
    I'm creating a new Client / Server application in C# and expect to have a fairly high rate of connections. That made me think of database connection pools which help mitigate the expense of creating and disposing connections between the client and database. I would like to create a similar capability for my application and haven't been able to find any good examples of how to apply this pattern. Do I really need to spin up an instance of a TcpClient every time I want to send a message to the server and receive a receipt message? Each connection is expected to transport between 1-5KB with each receiving a 1KB response message. I realize this question is somewhat vague, but I am starting from scratch so I am open to suggestions. Even if that means my suppositions are all wrong.

    Read the article

1 2 3 4 5  | Next Page >