Search Results

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

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

  • What happens if you break out of a Lock() statement?

    - by cyclotis04
    I'm writing a program which listens to an incoming TcpClient and handles data when it arrives. The Listen() method is run on a separate thread within the component, so it needs to be threadsafe. If I break out of a do while loop while I'm within a lock() statement, will the lock be released? If not, how do I accomplish this? Thanks! (Any other advice on the subject of Asynchronous TCP Sockets is welcome as well.) private void Listen() { do { lock (_client) { if (!_client.Connected) break; lock (_stateLock) { if (!_listening) break; if (_client.GetStream().DataAvailable) HandleData(); } } Thread.Sleep(0); } while (true); }

    Read the article

  • NetworkStream.Read delay .Net

    - by Gilbes
    I have a class that inherits from TcpClient. In that class I have a method to process responses. In that method I call I get the NetworkStream with MyBase.GetStream and call Read on it. This works fine, excpet the first call to read blocks too long. And by too long I mean that the socket has recieved plenty of data, but won't read it until some arbitrary limit is reached. I can see that it has recieved plenty of data using the packet sniffer WireShark. I have set the recieve buffer to small amounts, and very small amounts (like just a few bytes) to no avail. I have done the same with the buffer byte array I pass to the read method, and it still delays. Or to put it another way. I am download 600k. The download takes 5 seconds (at a little over 100k/second connection to the server which makes sense). The initial Read call takes 2-3 seconds and tells me only 256 bytes are availble (256 is the Recieve buffer and the size of the array I read in to). Then magically, the other few hundred thousand bytes can be read in 256 byte chunks in only a few process ticks each. Using a packet sniffer, I know that during those initial 2-3 seconds, the socket has recieved much more than just 256 bytes. My connection wasn't .25k/second for 3 seconds and then 400k for 2 seconds. How do I get the bytes from a socket as they come in?

    Read the article

  • Making an asynchronous Client with boost::asio

    - by tag
    Hello, i'm trying to make an asynchronous Client with boost::asio, i use the daytime asynchronous Server(in the tutorial). However sometimes the Client don't receive the Message, sometimes it do :O I'm sorry if this is too much Code, but i don't know what's wrong :/ Client: #include <iostream> #include <stdio.h> #include <ostream> #include <boost/thread.hpp> #include <boost/bind.hpp> #include <boost/array.hpp> #include <boost/asio.hpp> using namespace std; using boost::asio::ip::tcp; class TCPClient { public: TCPClient(boost::asio::io_service& IO_Service, tcp::resolver::iterator EndPointIter); void Write(); void Close(); private: boost::asio::io_service& m_IOService; tcp::socket m_Socket; boost::array<char, 128> m_Buffer; size_t m_BufLen; private: void OnConnect(const boost::system::error_code& ErrorCode, tcp::resolver::iterator EndPointIter); void OnReceive(const boost::system::error_code& ErrorCode); void DoClose(); }; TCPClient::TCPClient(boost::asio::io_service& IO_Service, tcp::resolver::iterator EndPointIter) : m_IOService(IO_Service), m_Socket(IO_Service) { tcp::endpoint EndPoint = *EndPointIter; m_Socket.async_connect(EndPoint, boost::bind(&TCPClient::OnConnect, this, boost::asio::placeholders::error, ++EndPointIter)); } void TCPClient::Close() { m_IOService.post( boost::bind(&TCPClient::DoClose, this)); } void TCPClient::OnConnect(const boost::system::error_code& ErrorCode, tcp::resolver::iterator EndPointIter) { if (ErrorCode == 0) // Successful connected { m_Socket.async_receive(boost::asio::buffer(m_Buffer.data(), m_BufLen), boost::bind(&TCPClient::OnReceive, this, boost::asio::placeholders::error)); } else if (EndPointIter != tcp::resolver::iterator()) { m_Socket.close(); tcp::endpoint EndPoint = *EndPointIter; m_Socket.async_connect(EndPoint, boost::bind(&TCPClient::OnConnect, this, boost::asio::placeholders::error, ++EndPointIter)); } } void TCPClient::OnReceive(const boost::system::error_code& ErrorCode) { if (ErrorCode == 0) { std::cout << m_Buffer.data() << std::endl; m_Socket.async_receive(boost::asio::buffer(m_Buffer.data(), m_BufLen), boost::bind(&TCPClient::OnReceive, this, boost::asio::placeholders::error)); } else { DoClose(); } } void TCPClient::DoClose() { m_Socket.close(); } int main() { try { boost::asio::io_service IO_Service; tcp::resolver Resolver(IO_Service); tcp::resolver::query Query("127.0.0.1", "daytime"); tcp::resolver::iterator EndPointIterator = Resolver.resolve(Query); TCPClient Client(IO_Service, EndPointIterator); boost::thread ClientThread( boost::bind(&boost::asio::io_service::run, &IO_Service)); std::cout << "Client started." << std::endl; std::string Input; while (Input != "exit") { std::cin >> Input; } Client.Close(); ClientThread.join(); } catch (std::exception& e) { std::cerr << e.what() << std::endl; } } Server: http://www.boost.org/doc/libs/1_39_0/doc/html/boost_asio/tutorial/tutdaytime3/src.html Regards :)

    Read the article

  • How to find cause and of the SocketException with message that an established connection was aborted

    - by cdpnet
    Hi All, I know the similar question may have been asked many times, but I want to represent the behavior I'm seeing and find if somebody can help predict the cause of this. I am writing a windows service which connects to other windows service over TCP. There are 100 user entities of this, and 5 connections per each. These users perform their tasks using their individual connections. The application goes on withough seeing this problem for 1 or 2 days. Or sometimes show the problem right after starting (-rarely). The best run I had was like 4 to 5 days without showing this exception. And after that application died or I had to stop it for various reasons. I want to know what can be causing this? Here is the stacktrace. System.IO.IOException: Unable to write data to the transport connection: An established connection was aborted by the software in your host machine. ---> System.Net.Sockets.SocketException: An established connection was aborted by the software in your host machine at System.Net.Sockets.Socket.Send(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags) at System.Net.Sockets.NetworkStream.Write(Byte[] buffer, Int32 offset, Int32 size) --- End of inner exception stack trace --- at System.Net.Sockets.NetworkStream.Write(Byte[] buffer, Int32 offset, Int32 size) at System.Net.Security._SslStream.StartWriting(Byte[] buffer, Int32 offset, Int32 count, AsyncProtocolRequest asyncRequest) at System.Net.Security._SslStream.ProcessWrite(Byte[] buffer, Int32 offset, Int32 count, AsyncProtocolRequest asyncRequest) at System.Net.Security.SslStream.Write(Byte[] buffer, Int32 offset, Int32 count)

    Read the article

  • Sending binary data with Indy through TCP\IP, how?

    - by Wodzu
    Hello. How to send a binary data with Indy components? Which of them is most suitable for this task? I've tried to use TIdTcpClient but it allows only to send strings. I've found one reponce for that problem here but I don't get it. It says about method Write(TIdBytes), but the answer is not clear for me. Does he meant Write to some instance of TIdBytes, and how to connect that instance with TIdTcpClient? Thanks for any help.

    Read the article

  • Cocoa NSStream TCP connection to FTP

    - by Chuck
    Hi, I'm new to Cocoa, but not to programming. Recently I decided I wanted to write a FTP client for Mac, and so I first made it in the language I'm most comfortable in (on Windows), and then moved on to Cocoa when I had the workings of FTP communications down. My question is (apparently) a bit controversial: How do I establish a read/writeable connection to (a ftp server)? What I have so far (non working obviously): NSInputStream *iStream; NSOutputStream *oStream; NSHost *host = [NSHost hostWithAddress:@"127.0.0.1"]; [NSStream getStreamsToHost:host port:3333 inputStream:&iStream outputStream:&oStream]; // ftp port: 3333 [iStream retain]; [oStream retain]; [iStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; [oStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; [iStream setDelegate:self]; [oStream setDelegate:self]; // which is not implemented apparently [iStream open]; [oStream open]; // .... [iStream write: (const uint8_t *)buf maxLength:8]; Which is partially based on http://developer.apple.com/mac/library/documentation/cocoa/Conceptual/Streams/Articles/NetworkStreams.html Now, why have I chosen NSStream? Because while this question is merely about how to connect to a FTP stream, my whole project will also include SSL and as far as I've been able to search here and on google, NSStream is capable of "switching" to a SSL connection. I've not been able to see the connection being made (which I'm usually able to do), but I also heard something about having to write to the stream before the stream will open? Any pointers are greatly appreciated, and sorry if my question is annoying - I'm new to Cocoa :)

    Read the article

  • How to measure the time taken by C# NetworkStream.Read?

    - by publicENEMY
    I want to measure time taken for client to receive data over tcp using c#. Im using NetworkStream.Read to read 100 megabits of data that are sent using NetworkStream.Write. I set the buffer to the same size of data, so there no buffer underrun problem etc. Generally it looks like this. Stopwatch sw = new Stopwatch(); sw.Start(); stream.Read(bytes, 0, bytes.Length); sw.Stop(); The problem is, there is a possibility where the sender hasnt actually sent the data but the stopwatch is already running. how can i accurately measure the time taken to receive the data? i did try to use the time lapse of the remote pc stream.Write, but the time it took to write is extremely small. by the way, is the stopwatch is the most accurate tool for this task?

    Read the article

  • C# equivalent of recv?

    - by mlh
    Hello, I have a portion of C code that I am trying to port over to C#. In my C code, I create a socket and then issue a receive command. The receive command is void receive(mysocket, char * command_buffer) { recv(mysocket, command_buffer, COMMAND_BUFFER_SIZE, 0); } now, the command buffer is returned with new values including command_buffer[8] being a pointer to a string. I'm really confused as to how to do this in C# because C# Read() command specifically takes in bytes and not char. The important part is that I get the pointer to the string. Any ideas?

    Read the article

  • Measure data transfer rate over tcp using c#

    - by publicENEMY
    i want to measure current download speed. im sending huge file over tcp. how can i capture the transfer rate every second? if i use IPv4InterfaceStatistics or similar method, instead of capturing the file transfer rate, i capture the device transfer rate. the problem with capturing device transfer rate is that it captures all ongoing data through the network device instead of the single file that i transfer. how can i capture the file transfer rate? im using c#.

    Read the article

  • How to find server is down,

    - by user363638
    I have client and server in unix machine, how can i find out my server is down and reconnect to server. without bringing my client down. I am doing connect (), but read() isiving me error Transport endpoint is already connected. I am using C++ in solaris. And what return value of read and connect should i check.

    Read the article

  • TCP/IP Implementation General Questions

    - by user2971023
    I've implemented the concepts shown here; http://wiki.unity3d.com/index.php/Simple_TCP/IP_Client_-_Server outside of unity and it works. (though i had to create the TCPIPServerApp from scratch as i could not find the base project anywhere). I have some general questions on how to use tcp/ip properly however. I've done some research on tcp/ip itself but I'm still a little confused. It seems like using the method above doesn't guarantee that I'll see the message (res). It just checks on every update to see if there is a different message in res. What if multiple messages are sent and the program lags or something, will i miss the earlier packet(s)? Should i instead do an array so it stores the last X messages? How do i know the data was received? Do I need to add a message id and build in my own ack into the data? Should i check to see if the port is in use before setting up a connection? Sorry for all the questions. This is all new to me but I enjoy this very much! ... Below already answered By Anton, Thanks It sounds like tcp uses its own packet numbering to ensure the packets end up in the right order on the other side. What if a packet is missed, are the subsequent packets thrown away? Or is this numbering and packet ordering, only for handling data that is broken out into multiple packets? TCP will automatically break the data into multiple packets if necessary right?

    Read the article

  • multiple threads writting to a same socket problem

    - by alex
    Hi: My program uses sockets for inter-process communication. There is one server listening on a socket port(B) on localhost waiting for a list of TCP clients to connect. And on the other end of the server is another a socket(A) that sends out data to internet. The server is designed to take everything the TCP clients send him and forward to a server on the internet. My question is if two of the TCP clients happened to send data at the same time, is this going to be a problem for the server's outgoing socket(A)? Thanks

    Read the article

  • How do I parse data received in a memorystream?

    - by Kerberos42
    I'm new to using sockets. I have a very basic client that sends a request, and waits for a response. The response is one stream, but has two parts. The first part is prefixed with ANS and is a set of key/value pairs in this form: KEY:Value with each pair on a separate line. The second part of the response is prefixed by RCT and this is pre-formatted text that needs to be send directly to a printer. So what would be the best way to extract both parts of the response, and in the first part, get each Key:Value pair. I might not even need them all, but I have to look at each one to see what the values are then decide what to do with it. I'm currently writing the response out to a textbox just to understand what its doing, but now I need to actually do something with the data. Here's a data sample, as it is received: ANS Result: Data Received RCPRES:Q[81] TML:123 OPP: MRR:000000999999 <several dozen more KEY:Value pairs> RCTNov 05 2013 04:03 pm Trans# 123456 <pre-formatted text>

    Read the article

  • Concurrent connections in C# socket

    - by Chu Mai
    There are three apps run at the same time, 2 clients and 1 server. The whole system should function as following: The client sends an serialized object to server then server receives that object as a stream, finally the another client get that stream from server and deserialize it. This is the sender: TcpClient tcpClient = new TcpClient(); tcpClient.Connect("127.0.0.1", 8888); Stream stream = tcpClient.GetStream(); BinaryFormatter binaryFormatter = new BinaryFormatter(); binaryFormatter.Serialize(stream, event); // Event is the sending object tcpClient.Close(); Server code: TcpListener listener = new TcpListener(IPAddress.Parse("127.0.0.1"), 8888); listener.Start(); Console.WriteLine("Server is running at localhost port 8888 "); while (true) { Socket socket = listener.AcceptSocket(); try { Stream stream = new NetworkStream(socket); // Typically there should be something to write the stream // But I don't knwo exactly what should the stream write } catch (Exception e) { Console.WriteLine("Exception: " + e.Message); Console.WriteLine("Disconnected: {0}", socket.RemoteEndPoint); } } The receiver: TcpClient client = new TcpClient(); // Connect the client to the localhost with port 8888 client.Connect("127.0.0.1", 8888); Stream stream = client.GetStream(); Console.WriteLine(stream); when I run only the sender and server, and check the server, server receives correctly the data. The problem is when I run the receiver, everything is just disconnected. So where is my problem ? Could anyone point me out ? Thanks

    Read the article

  • Unable to write data to the transport connection: An existing connection was forcibly closed by the remote host

    - by xnoor
    i have an update server that sends client updates through TCP port 12000, the sending of a single file is successful only the first time, but after that i get an error message on the server "Unable to write data to the transport connection: An existing connection was forcibly closed by the remote host", if i restart the update service on the server, it works again only one, i have normal multithreaded windows service SERVER CODE namespace WSTSAU { public partial class ApplicationUpdater : ServiceBase { private Logger logger = LogManager.GetCurrentClassLogger(); private int _listeningPort; private int _ApplicationReceivingPort; private string _setupFilename; private string _startupPath; public ApplicationUpdater() { InitializeComponent(); } protected override void OnStart(string[] args) { init(); logger.Info("after init"); Thread ListnerThread = new Thread(new ThreadStart(StartListener)); ListnerThread.IsBackground = true; ListnerThread.Start(); logger.Info("after thread start"); } private void init() { _listeningPort = Convert.ToInt16(ConfigurationSettings.AppSettings["ListeningPort"]); _setupFilename = ConfigurationSettings.AppSettings["SetupFilename"]; _startupPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase).Substring(6); } private void StartListener() { try { logger.Info("Listening Started"); ThreadPool.SetMinThreads(50, 50); TcpListener listener = new TcpListener(_listeningPort); listener.Start(); while (true) { TcpClient c = listener.AcceptTcpClient(); ThreadPool.QueueUserWorkItem(ProcessReceivedMessage, c); } } catch (Exception ex) { logger.Error(ex.Message); } } void ProcessReceivedMessage(object c) { try { TcpClient tcpClient = c as TcpClient; NetworkStream Networkstream = tcpClient.GetStream(); 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.ApplicationUpdateMessage: ApplicationUpdateMessage appUpdateMessage = new ApplicationUpdateMessage(); appUpdateMessage = SerializationManager.XmlFormatterByteArrayToObject(messageContainer.messageContnet, appUpdateMessage) as ApplicationUpdateMessage; Func<ApplicationUpdateMessage, bool> HandleUpdateRequestMethod = HandleUpdateRequest; IAsyncResult cookie = HandleUpdateRequestMethod.BeginInvoke(appUpdateMessage, null, null); bool WorkerThread = HandleUpdateRequestMethod.EndInvoke(cookie); break; } } catch (Exception ex) { logger.Error(ex.Message); } } private bool HandleUpdateRequest(ApplicationUpdateMessage appUpdateMessage) { try { TcpClient tcpClient = new TcpClient(); NetworkStream networkStream; FileStream fileStream = null; tcpClient.Connect(appUpdateMessage.receiverIpAddress, appUpdateMessage.receiverPortNumber); networkStream = tcpClient.GetStream(); fileStream = new FileStream(_startupPath + "\\" + _setupFilename, FileMode.Open, FileAccess.Read); FileInfo fi = new FileInfo(_startupPath + "\\" + _setupFilename); BinaryReader binFile = new BinaryReader(fileStream); FileUpdateMessage fileUpdateMessage = new FileUpdateMessage(); fileUpdateMessage.fileName = fi.Name; fileUpdateMessage.fileSize = fi.Length; 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 { } } protected override void OnStop() { } } i have to note something that my windows service (server) is multithreaded.. i hope anyone can help with this

    Read the article

  • get length of data sent over network to TCPlistener/networkstream vb.net

    - by Jonathan.
    It seems the most obvious thing, but I just can't work out how to get the length of bytes sent over a network using a TCPClient and TCPListener? This is my code so far: 'Must listen on correct port- must be same as port client wants to connect on. Const portNumber As Integer = 9999 Dim tcpListener As New TcpListener(IPAddress.Parse("192.168.2.7"), portNumber) tcpListener.Start() Console.WriteLine("Waiting for connection...") 'Accept the pending client connection and return 'a TcpClient initialized for communication. Dim tcpClient As TcpClient = tcpListener.AcceptTcpClient() Console.WriteLine("Connection accepted.") ' Get the stream Dim networkStream As NetworkStream = tcpClient.GetStream() '' Read the stream into a byte array I need to get the length of the networkstream to set the size of the array of bytes I'm going to read the data into. But the networkStream.length is unsupported and does not work and throws an Notsupportedexception. The only other way I can think of is to send the size of the data before sending the data, but this seems the long way round.

    Read the article

  • android client not working [migrated]

    - by Syeda Zunairah
    i have a java client and c# server the server code is static Socket listeningSocket; static Socket socket; static Thread thrReadRequest; static int iPort = 4444; static int iConnectionQueue = 100; static void Main(string[] args) { Console.WriteLine(IPAddress.Parse(getLocalIPAddress()).ToString()); try { listeningSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //listeningSocket.Bind(new IPEndPoint(0, iPort)); listeningSocket.Bind(new IPEndPoint(IPAddress.Parse(getLocalIPAddress()), iPort)); listeningSocket.Listen(iConnectionQueue); thrReadRequest = new Thread(new ThreadStart(getRequest)); thrReadRequest.Start(); } catch (Exception e) { Console.WriteLine("Winsock error: " + e.ToString()); //throw; } } static private void getRequest() { int i = 0; while (true) { i++; Console.WriteLine("Outside Try i = {0}", i.ToString()); try { socket = listeningSocket.Accept(); // Receiving //byte[] rcvLenBytes = new byte[4]; //socket.Receive(rcvLenBytes); //int rcvLen = System.BitConverter.ToInt32(rcvLenBytes, 0); //byte[] rcvBytes = new byte[rcvLen]; //socket.Receive(rcvBytes); //String formattedBuffer = System.Text.Encoding.ASCII.GetString(rcvBytes); byte[] buffer = new byte[socket.SendBufferSize]; int iBufferLength = socket.Receive(buffer, 0, buffer.Length, 0); Console.WriteLine("Received {0}", iBufferLength); Array.Resize(ref buffer, iBufferLength); string formattedBuffer = Encoding.ASCII.GetString(buffer); Console.WriteLine("Data received by Client: {0}", formattedBuffer); if (formattedBuffer == "quit") { socket.Close(); listeningSocket.Close(); Environment.Exit(0); } Console.WriteLine("Inside Try i = {0}", i.ToString()); Thread.Sleep(500); } catch (Exception e) { //socket.Close(); Console.WriteLine("Receiving error: " + e.ToString()); Console.ReadKey(); //throw; } finally { socket.Close(); //listeningsocket.close(); } } } static private string getLocalIPAddress() { IPHostEntry host; string localIP = ""; host = Dns.GetHostEntry(Dns.GetHostName()); foreach (IPAddress ip in host.AddressList) { if (ip.AddressFamily == AddressFamily.InterNetwork) { localIP = ip.ToString(); break; } } return localIP; } } and the jave android code is private TCPClient mTcpClient; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final EditText editText = (EditText) findViewById(R.id.edit_message); Button send = (Button)findViewById(R.id.sendbutton); // connect to the server new connectTask().execute(""); send.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String message = editText.getText().toString(); //sends the message to the server if (mTcpClient != null) { mTcpClient.sendMessage(message); } editText.setText(""); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } public class connectTask extends AsyncTask<String,String,TCPClient> { @Override protected TCPClient doInBackground(String... message) { mTcpClient = new TCPClient(new TCPClient.OnMessageReceived() { @Override public void messageReceived(String message) { publishProgress(message); } }); mTcpClient.run(); return null; } @Override protected void onProgressUpdate(String... values) { super.onProgressUpdate(values); } } } when i run the server it gives output of try i=1. can any one tell me what to do next

    Read the article

  • How to use CFNetwork to get byte array from sockets?

    - by Vic
    Hi, I'm working in a project for the iPad, it is a small program and I need it to communicate with another software that runs on windows and act like a server; so the application that I'm creating for the iPad will be the client. I'm using CFNetwork to do sockets communication, this is the way I'm establishing the connection: char ip[] = "192.168.0.244"; NSString *ipAddress = [[NSString alloc] initWithCString:ip]; /* Build our socket context; this ties an instance of self to the socket */ CFSocketContext CTX = { 0, self, NULL, NULL, NULL }; /* Create the server socket as a TCP IPv4 socket and set a callback */ /* for calls to the socket's lower-level connect() function */ TCPClient = CFSocketCreate(NULL, PF_INET, SOCK_STREAM, IPPROTO_TCP, kCFSocketDataCallBack, (CFSocketCallBack)ConnectCallBack, &CTX); if (TCPClient == NULL) return; /* Set the port and address we want to listen on */ struct sockaddr_in addr; memset(&addr, 0, sizeof(addr)); addr.sin_len = sizeof(addr); addr.sin_family = AF_INET; addr.sin_port = htons(PORT); addr.sin_addr.s_addr = inet_addr([ipAddress UTF8String]); CFDataRef connectAddr = CFDataCreate(NULL, (unsigned char *)&addr, sizeof(addr)); CFSocketConnectToAddress(TCPClient, connectAddr, -1); CFRunLoopSourceRef sourceRef = CFSocketCreateRunLoopSource(kCFAllocatorDefault, TCPClient, 0); CFRunLoopAddSource(CFRunLoopGetCurrent(), sourceRef, kCFRunLoopCommonModes); CFRelease(sourceRef); CFRunLoopRun(); And this is the way I sent the data, which basically is a byte array /* The native socket, used for various operations */ // TCPClient is a CFSocketRef member variable CFSocketNativeHandle sock = CFSocketGetNative(TCPClient); Byte byteData[3]; byteData[0] = 0; byteData[1] = 4; byteData[2] = 0; send(sock, byteData, strlen(byteData)+1, 0); Finally, as you may have noticed, when I create the server socket, I registered a callback for the kCFSocketDataCallBack type, this is the code. void ConnectCallBack(CFSocketRef socket, CFSocketCallBackType type, CFDataRef address, const void *data, void *info) { // SocketsViewController is the class that contains all the methods SocketsViewController *obj = (SocketsViewController*)info; UInt8 *unsignedData = (UInt8 *) CFDataGetBytePtr(data); char *value = (char*)unsignedData; NSString *text = [[NSString alloc]initWithCString:value length:strlen(value)]; [obj writeToTextView:text]; [text release]; } Actually, this callback is being invoked in my code, the problem is that I don't know how can I get the data that the windows client sent me, I'm expecting to receive an array of bytes, but I don't know how can I get those bytes from the data param. If anyone can help me to find a way to do this, or maybe me point me to another way to get the data from the server in my client application I would really appreciate it. Thanks.

    Read the article

  • tcp/ip accept not returning, but client does

    - by paquetp
    server: vxworks 6.3 calls the usual socket, bind, listen, then: for (;;) { client = accept(sfd,NULL,NULL); // pass client to worker thread } client: .NET 2.0 TcpClient constructor to connect to server that takes the string hostname and int port, like: TcpClient client = new TcpClient(server_ip, port); This is working fine when the server is compiled and executed in windows (native c++). intermittently, the constructor to TcpClient will return the instance, without throwing any exception, but the accept call in vxWorks does not return with the client fd. tcpstatShow indicates no accept occurred. What could possibly make the TcpClient constructor (which calls 'Connect') return the instance, while the accept call on the server not return? It seems to be related to what the system is doing in the background - it seems more likely to get this symptom to occur when the server is busy persisting data to flash or an NFS share when the client attempts to connect, but can happen when it isn't also. I've tried adjusting priority of the thread running accept I've looked at the size of the queue in 'listen'. There's enough. The total number of file descriptors available should be enough (haven't validated this yet though, first thing in the morning)

    Read the article

  • Raw FTP SSL with C#

    - by Chuck
    Hi, I'm trying to understand how SSL works. In my wish to make a small FTP client which supports SSL I've run into some problems: TcpClient FtpConnection = new TcpClient(FtpServer, FtpPort); NetworkStream FtpStream = FtpConnection.GetStream(); StreamReader FtpReader = new StreamReader(FtpStream); FtpWriter = new StreamWriter(IrcStream); send_cmd("AUTH SSL"); send_cmd is just a FtpWriter.WriteLine(text); FtpWriter.Flush(); function. My "problem" is this: First I need to make a (non-ssl) connection to the FTP, then tell it to do a ssl connection (AUTH SSL), and I would guess I then need to make a new connection - something like: TcpClient client = new TcpClient(FtpServer, FtpPort); SslStream sslStream = new SslStream(client.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null); try { sslStream.AuthenticateAsClient("foobar"); } catch (AuthenticationException e) { MessageBox.Show("Authentication failed - closing the connection."); client.Close(); return; } Taken from msdn. I keep dying on handshake failed due to unexpected packet format (which I've tried googling, but all say it's because the author has connected to a wrong port), which I take as: The connection is not ssl until AUTH SSL is send to it. So my question is, how would i go about making this a "hybrid" connection so I can make an SSL connection to the server? Any help is greatly appreciated!

    Read the article

  • Reading and writing XML over an SslStream

    - by Mark
    I want to read and write XML data over an SslStream. The data (written and read) consists of objects serialized by an XmlSerializer. I have tried the following; (left some details out for clarity!) TcpClient tcpClient = new TcpClient(server, port); SslStream sslStream = new SslStream(tcpClient.GetStream(), true, new RemoteCertificateValidationCallback(ValidateServerCertificate), null); sslStream.AuthenticateAsClient(server); XmlReader xmlReader = XmlReader.Create(sslStream,readerSettings); XmlWriter xmlWriter = XmlWriter.Create(sslStream,writerSettings); myClass c = new myClass (); XmlSerializer serializer = new XmlSerializer(typeof(myClass)); serializer.Serialize(xmlWriter, c); myClass c2 = (myClass )serializer.Deserialize(xmlReader); First of all, it appears that writing to the stream succeeds. But the XmlSerializer throws an error because of invalid XML. It appears that the first character read from the stream is '00' or a null-character. (I have googled this problem, and see a million people with the same 'problem', but no viable solution.) I can work around this 'issue' by using a StreamReader, read everything into a string and then use that string as input for another stream that the serializer can use. (Very dirty, but it works.) Second problem is, that when I try to use the same SslStream to write a second request, I do not get a response from the Reader. (The server DOES send a valid XML response though!) So the serializer.Serialize(xmlWriter, c3) works, but reading from the stream yields no results. I have tried several different classes that implement Stream. (StreamReader, XmlTextReader, etc.) Anyone has an idea how reading and writing XML data to and from an SslStream is supposed to work? Thanks in advance!

    Read the article

  • Socket - Adress already in use

    - by Hamza Karmouda
    I'm new to socketand i try to code an Server and client on the same application just to see how it work. here's my code : public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); ((Button)this.findViewById(R.id.bouton1)).setOnClickListener(this); } public void onClick(View v) { TCPServer server = new TCPServer(); TCPClient client = new TCPClient(); server.start(); client.start(); } public class TCPServer extends Thread { @Override public void run() { try { ServerSocket s = new ServerSocket(8080,0,InetAddress.getLocalHost()); Socket cli = s.accept(); byte[] b = new byte[512]; int n; InputStream is = cli.getInputStream(); while((n=is.read(b))>0){ Log.d("TCPServer",new String(b)); if(new String(b).contains("\r\n\r\n"))break; b = new byte[512]; } OutputStream os = cli.getOutputStream(); os.write("Hello".getBytes()); } catch (Exception e) { e.printStackTrace(); } } } public class TCPClient extends Thread { @Override public void run() { try { Socket s = new Socket(InetAddress.getLocalHost().getHostAddress(),8080); //Socket s = new Socket("www.google.com",80); //Log.i("",s.getLocalAddress().getHostAddress()); byte[] b = new byte[512]; int n; if (s.isConnected()) { OutputStream os = s.getOutputStream(); os.write("Hi How are you \r\n\r\n".getBytes()); InputStream is = s.getInputStream(); while((n=is.read(b))>0){ Log.d("TCPClient",new String(b)); b = new byte[512]; } } s.close(); } catch (Exception e) { e.printStackTrace(); } } } the code work fine but just for the first time i click my button. the error is java.net.BindException: Address already in use .

    Read the article

  • C++/CLI HTTP Proxy problems...

    - by darkantimatter
    Hi, I'm trying(very hard) to make a small HTTP Proxy server which I can use to save all communications to a file. Seeing as I dont really have any experience in the area, I used a class from codeproject.com and some associated code to get started (It was made in the old CLI syntax, so I converted it). I couldn't get it working, so I added lots more code to make it work (threads etc), and now it sort of works. Basically, it recieves something from a client (I just configured Mozilla Firefox to route its connections through this proxy) and then routes it to google.com. After it sends Mozilla's data to google, recieves a responce, and sends that to Mozilla. This works fine, but then the proxy fails to recieve any data from Mozilla. It just loops in the Sleep(50) section. Anyway, heres the code: ProxyTest.cpp: #include "stdafx.h" #include "windows.h" #include "CHTTPProxy.h" public ref class ClientThread { public: System::Net::Sockets::TcpClient ^ pClient; CHttpProxy ^ pProxy; System::Int32 ^ pRecieveBufferSize; System::Threading::Thread ^ Thread; ClientThread(System::Net::Sockets::TcpClient ^ sClient, CHttpProxy ^ sProxy, System::Int32 ^ sRecieveBufferSize) { pClient = sClient; pProxy = sProxy; pRecieveBufferSize = sRecieveBufferSize; }; void StartReading() { Thread = gcnew System::Threading::Thread(gcnew System::Threading::ThreadStart(this,&ClientThread::ThreadEntryPoint)); Thread->Start(); }; void ThreadEntryPoint() { char * bytess; bytess = new char[(int)pRecieveBufferSize]; memset(bytess, 0, (int)pRecieveBufferSize); array<unsigned char> ^ bytes = gcnew array<unsigned char>((int)pRecieveBufferSize); array<unsigned char> ^ sendbytes; do { if (pClient->GetStream()->DataAvailable) { try { do { Sleep(100); //Lets wait for whole packet to get cached (If it even does...) unsigned int k = pClient->GetStream()->Read(bytes, 0, (int)pRecieveBufferSize); //Read it for(unsigned int i=0; i<(int)pRecieveBufferSize; i++) bytess[i] = bytes[i]; Console::WriteLine("Packet Received:\n"+gcnew System::String(bytess)); pProxy->SendToServer(bytes,pClient->GetStream()); //Now send it to google! pClient->GetStream()->Flush(); } while(pClient->GetStream()->DataAvailable); } catch (Exception ^ e) { break; } } else { Sleep(50); //It just loops here because it thinks mozilla isnt sending anything if (!(pClient->Connected)) break; }; } while (pClient->GetStream()->CanRead); delete [] bytess; pClient->Close(); }; }; int main(array<System::String ^> ^args) { System::Collections::Generic::Stack<ClientThread ^> ^ Clients = gcnew System::Collections::Generic::Stack<ClientThread ^>(); System::Net::Sockets::TcpListener ^ pTcpListener = gcnew System::Net::Sockets::TcpListener(8080); pTcpListener->Start(); System::Net::Sockets::TcpClient ^ pTcpClient; while (1) { pTcpClient = pTcpListener->AcceptTcpClient(); //Wait for client ClientThread ^ Client = gcnew ClientThread(pTcpClient, gcnew CHttpProxy("www.google.com.au", 80), pTcpClient->ReceiveBufferSize); //Make a new object for this client Client->StartReading(); //Start the thread Clients->Push(Client); //Add it to the list }; pTcpListener->Stop(); return 0; } CHTTPProxy.h, from http://www.codeproject.com/KB/IP/howtoproxy.aspx with a lot of modifications: //THIS FILE IS FROM http://www.codeproject.com/KB/IP/howtoproxy.aspx. I DID NOT MAKE THIS! BUT I HAVE MADE SEVERAL MODIFICATIONS! #using <mscorlib.dll> #using <SYSTEM.DLL> using namespace System; using System::Net::Sockets::TcpClient; using System::String; using System::Exception; using System::Net::Sockets::NetworkStream; #include <stdio.h> ref class CHttpProxy { public: CHttpProxy(System::String ^ szHost, int port); System::String ^ m_host; int m_port; void SendToServer(array<unsigned char> ^ Packet, System::Net::Sockets::NetworkStream ^ sendstr); }; CHttpProxy::CHttpProxy(System::String ^ szHost, int port) { m_host = gcnew System::String(szHost); m_port = port; } void CHttpProxy::SendToServer(array<unsigned char> ^ Packet, System::Net::Sockets::NetworkStream ^ sendstr) { TcpClient ^ tcpclnt = gcnew TcpClient(); try { tcpclnt->Connect(m_host,m_port); } catch (Exception ^ e ) { Console::WriteLine(e->ToString()); return; } // Send it if ( tcpclnt ) { NetworkStream ^ networkStream; networkStream = tcpclnt->GetStream(); int size = Packet->Length; networkStream->Write(Packet, 0, size); array<unsigned char> ^ bytes = gcnew array<unsigned char>(tcpclnt->ReceiveBufferSize); char * bytess = new char[tcpclnt->ReceiveBufferSize]; Sleep(500); //Wait for responce do { unsigned int k = networkStream->Read(bytes, 0, (int)tcpclnt->ReceiveBufferSize); //Read from google for(unsigned int i=0; i<k; i++) { bytess[i] = bytes[i]; if (bytess[i] == 0) bytess[i] = ' '; //Dont terminate the string if (bytess[i] < 8) bytess[i] = ' '; //Somethings making the computer beep, and its not 7?!?! }; Console::WriteLine("\n\nAbove packet sent to google. Google Packet Received:\n"+gcnew System::String(bytess)); sendstr->Write(bytes,0,k); //Send it to mozilla Console::WriteLine("\n\nAbove packet sent to client..."); //Sleep(1000); } while(networkStream->DataAvailable); delete [] bytess; } return; } Any help would be much appreciated, I've tried for hours.

    Read the article

< Previous Page | 1 2 3 4 5  | Next Page >