Search Results

Search found 5206 results on 209 pages for 'dr rocket mr socket'.

Page 8/209 | < Previous Page | 4 5 6 7 8 9 10 11 12 13 14 15  | Next Page >

  • socket.accept error 24: To many open files

    - by Creotiv
    I have a problem with open files under my Ubuntu 9.10 when running server in Python2.6 And main problem is that, that i don't know why it so.. I have set ulimit -n = 999999 net.core.somaxconn = 999999 fs.file-max = 999999 and lsof gives me about 12000 open files when server is running. And also i'm using epoll. But after some time it's start giving exeption: File "/usr/lib/python2.6/socket.py", line 195, in accept error: [Errno 24] Too many open files And i don't know how it can reach file limit when it isn't reached. Thanks for help)

    Read the article

  • Socket programming question

    - by dfddf
    I am given the following declaration: char inbuff[500], *ptr; int n, bufferlen; Write a program segement to receive a message having 500 bits from the TCP socket sock and store this message in inbuff. My answer is: n = recv( sock, inbuff, strlen( inbuff ), 0 ); However, I am not sure why *ptr is given in the declaration. So, I would like ask, what is the purpose of the pointer in this question?? Or my program segement is wrong? Thank you for all of yours help first!

    Read the article

  • setsockopt (sys/socket.h)

    - by lojin
    The prototype for setsockopt is: int setsockopt(int socket, int level, int option_name, const void *option_value, socklen_t option_len); Are the following all correct ? Which are not ? a.) int buffsize = 50000; setsockopt(s, SOL_SOCKET, SO_RCVBUF, (char *)&buffsize, sizeof(buffsize)); b.) int buffsize = 50000; setsockopt(s, SOL_SOCKET, SO_RCVBUF, (void *)&buffsize, sizeof(buffsize)); c.) char *buffsize = "50000"; setsockopt(s, SOL_SOCKET, SO_RCVBUF, buffsize, strlen(buffsize)); d.) setsockopt(s, SOL_SOCKET, SO_RCVBUF, "50000", 5);

    Read the article

  • Security sandbox violation when connecting to Socket from flex

    - by KensoDev
    Hi, I am using a Socket (not xmlSocket) connection between flex applications and the server pushing messages. Now, when I connect from the local machine to the server everything is working file and running, connection is succesful and I get data back and forth. When I upload the application (flex) to the server and run it from there, I get a security sandBox violation message. Note: 1. I do have a crossdomain file with * wildcard both on port and on domain. 2. I created a Securiy.allowDomain("*") as well. Another thing. I also created another listener on that same server, listening to connections for port 843 (default) and this service just waited for a connection send policy file to the client and that's it. That did not solve the problem as well... That's next? What should I do to fix the problem? Appreciate your help. Avi

    Read the article

  • Reason for not properly closed socket?

    - by gc
    Here is what I am trying to do: The server sends message to connected clients when new messages are available. The client, on the other hand, when connected, tries to send a message to the server using send() and then receive message using recv(), right after that, the client calls close() to close the connection. Sometimes, after the client finishes, the server tries to receive message from client will result in a 104 - "connection reset by peer" error. When this happens, Wireshark reveals that the last two segments sent by the client is: 1. an ACK acknowledging the receipt of the message sent by the server 2. a RST/ACK No FIN is sent by the client. Why is this happening and how can I close the socket "properly" at the client?

    Read the article

  • How can I set the buffer size for the underneath Socket UDP? C#

    - by Jack
    Hi all As we know for UDP receive, we use Socket.ReceiveFrom or UdpClient.receive Socket.ReceiveFrom accept a byte array from you to put the udp data in. UdpClient.receive returns directly a byte array where the data is My question is that How to set the buffer size inside Socket. I think the OS maintains its own buffer for receive UDP data, right? for e.g., if a udp packet is sent to my machine, the OS will put it to a buffer and wait us to Socket.ReceiveFrom or UdpClient.receive, right? How can I change the size of that internal buffer? I have tried Socket.ReceiveBuffSize, it has no effect at all for UDP, and it clearly said that it is for TCP window. Also I have done a lot of experiments which proves Socket.ReceiveBufferSize is NOT for UDP. Can anyone share some insights for UDP internal buffer??? Thanks

    Read the article

  • AS3 / Java - Socket Connection from live Flash to local java

    - by PitchBlackCat
    Hey guys, I'm trying to get a live flash that lives on a webserver to talk to a local java server, that will live on the clients PC. I'm trying to achieve this with a socket connection. (port 6000) Now, at first flash was able to connect, but it just sends <policy-file-request/>. After this nothing happens. Now, some people at Kirupa suggested to send an cross-domain-policy xml as soon as any connection is established from the java side. http://www.kirupa.com/forum/showthread.php?t=301625 However, my java server just throws the following: End Exception: java.net.SocketException: Software caused connection abort: recv failed I've already spend a great amount of time on this subject, and was wondering if anyone here knows what to do?

    Read the article

  • New thread per client connection in socket server?

    - by Olaseni
    I am trying to optimize multiple connections per time to a TCP socket server. Is it considered good practice, or even rational to initiate a new thread in the listening server every time I receive a connection request? At what time should I begin to worry about a server based on this infrastructure? What is the maximum no of background threads I can work, until it doesn't make any sense anymore? Platform is C#, framework is Mono, target OS is CentOS, RAM is 2.4G, server is on the clouds, and I'm expecting about 200 connection requests per second.

    Read the article

  • How to determine IP used by client connecting to INADDR_ANY listener socket in C

    - by codebox_rob
    I have a network server application written in C, the listener is bound using INADDR_ANY so it can accept connections via any of the IP addresses of the host on which it is installed. I need to determine which of the server's IP addresses the client used when establishing its connection - actually I just need to know whether they connected via the loopback address 127.0.0.1 or not. Partial code sample as follows (I can post the whole thing if it helps): static struct sockaddr_in serverAddress; serverAddress.sin_family = AF_INET; serverAddress.sin_addr.s_addr = INADDR_ANY; serverAddress.sin_port = htons(port); bind(listener, (struct sockaddr *) &serverAddress, sizeof(serverAddress)); listen(listener, CONNECTION_BACKLOG); SOCKET socketfd; static struct sockaddr_in clientAddress; ... socketfd = accept(listener, (struct sockaddr *) &clientAddress, &length);

    Read the article

  • Socket.io Duplicate clients on a namespace

    - by Servernumber
    Hi I'm trying to use dynamic namespace to create them on demand. It's working except that I get duplicate or more client for some reason Server side : io.of("/" + group ).on("connection", function(socket_group) { socket_group.groupId = group; socket_group.on("infos", function(){ console.log("on the group !"); }) socket_group.on('list', function () { Urls.find({'group' : '...'}).sort({ '_id' : -1 }).limit(10).exec(function(err, data){ socket_group.emit('links', data); }); }) [...] }) Client Side : socket.emit('list', { ... }); On the client side only one command is sent but the server is always responding with 2 or more responses. Every time I close/open my app the response is incremented. Thanks if you find out.

    Read the article

  • Python: Matching & Stripping port number from socket data

    - by tobywuk
    Hello, I have data coming in to a python server via a socket. Within this data is the string '<port>80</port>' or which ever port is being used. I wish to extract the port number into a variable. The data coming in is not XML, I just used the tag approach to identifying data for future XML use if needed. I do not wish to use an XML python library, but simply use something like regexp and strings. What would you recommend is the best way to match and strip this data? I am currently using this code with no luck: p = re.compile('<port>\w</port>') m = p.search(data) print m Thank you :)

    Read the article

  • Transmission and verification of certificate (openssl) with socket in c

    - by allenzzzxd
    Hello, guys, I have to write these codes in c. I have already generate the certificate of one terminate t1: t1.pem, which is generated by openssl. The communication between the terminates t1 and t2 has been established via socket in c. Now I want to send this certificate to another terminate t2.and I want t2 to receive the certificate, verify it and answer with an acceptance to t1. When t1 get this acceptance, it will the rest of stuffs.. But I don't know how to do these things. For example, I transmit t1.pem as a string? But in t2 side, how can I do to verify? I know there are functions in openssl to do so, but I'm not so clear about it. At last, normally, the acceptance should be like how? @[email protected] lot of questions here.. sorry...if someone could give me some guide.. Thanks a lot in advance!

    Read the article

  • Problem when trying to connect to a desktop server from android on wifi

    - by thiagolee
    Hello, I am trying to send a file from the phone running Android 1.5 to a server on a desktop. I wrote some code, which works on emulator, but on the phone it doesn't. I'm connecting to the network through WiFi. It works, I can access the internet through my phone and I've configured my router. The application stops when I'm trying to connect. I have the permissions. Someone have any ideas, below is my code. Running on Android package br.ufs.reconhecimento; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.net.Socket; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.EditText; import android.widget.ImageButton; /** * Sample code that invokes the speech recognition intent API. */ public class Reconhecimento extends Activity implements OnClickListener { static final int VOICE_RECOGNITION_REQUEST_CODE = 1234; static final String LOG_VOZ = "UFS-Reconhecimento"; final int INICIAR_GRAVACAO = 01; int porta = 5158; // Porta definida no servidor int tempoEspera = 1000; String ipConexao = "172.20.0.189"; EditText ipEdit; /** * Called with the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Inflate our UI from its XML layout description. setContentView(R.layout.main); // Get display items for later interaction ImageButton speakButton = (ImageButton) findViewById(R.id.btn_speak); speakButton.setPadding(10, 10, 10, 10); speakButton.setOnClickListener(this); //Alerta para o endereço IP AlertDialog.Builder alerta = new AlertDialog.Builder(this); alerta.setTitle("IP");//+mainWifi.getWifiState()); ipEdit = new EditText(this); ipEdit.setText(ipConexao); alerta.setView(ipEdit); alerta.setMessage("Por favor, Confirme o endereço IP."); alerta.setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { ipConexao = ipEdit.getText().toString(); Log.d(LOG_VOZ, "Nova Atribuição do Endreço IP: " + ipConexao); } }); alerta.create(); alerta.show(); } /** * Handle the click on the start recognition button. */ public void onClick(View v) { if (v.getId() == R.id.btn_speak) { //startVoiceRecognitionActivity(); Log.d(LOG_VOZ, "Iniciando a próxima tela"); Intent recordIntent = new Intent(this, GravacaoAtivity.class); Log.d(LOG_VOZ, "Iniciando a tela (instancia criada)"); startActivityForResult(recordIntent, INICIAR_GRAVACAO); Log.d(LOG_VOZ, "Gravação iniciada ..."); } } /** * Handle the results from the recognition activity. */ @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { Log.d(LOG_VOZ, "Iniciando onActivityResult()"); if (requestCode == INICIAR_GRAVACAO && resultCode == RESULT_OK) { String path = data.getStringExtra(GravacaoAtivity.RETORNO); conexaoSocket(path); } else Log.e(LOG_VOZ, "Resultado Inexperado ..."); } private void conexaoSocket(String path) { Socket socket = SocketOpener.openSocket(ipConexao, porta, tempoEspera); if(socket == null) return; try { DataOutputStream conexao = new DataOutputStream(socket.getOutputStream()); Log.d(LOG_VOZ, "Acessando arquivo ..."); File file = new File(path); DataInputStream arquivo = new DataInputStream(new FileInputStream(file)); Log.d(LOG_VOZ, "Iniciando Transmissão ..."); conexao.writeLong(file.length()); for(int i = 0; i < file.length(); i++) conexao.writeByte(arquivo.readByte()); Log.d(LOG_VOZ, "Transmissão realizada com sucesso..."); Log.d(LOG_VOZ, "Fechando a conexão..."); conexao.close(); socket.close(); Log.d(LOG_VOZ, "============ Processo finalizado com Sucesso =============="); } catch (IOException e) { Log.e(LOG_VOZ, "Erro ao fazer a conexão via Socket. " + e.getMessage()); // TODO Auto-generated catch block } } } class SocketOpener implements Runnable { private String host; private int porta; private Socket socket; public SocketOpener(String host, int porta) { this.host = host; this.porta = porta; socket = null; } public static Socket openSocket(String host, int porta, int timeOut) { SocketOpener opener = new SocketOpener(host, porta); Thread t = new Thread(opener); t.start(); try { t.join(timeOut); } catch(InterruptedException e) { Log.e(Reconhecimento.LOG_VOZ, "Erro ao fazer o join da thread do socket. " + e.getMessage()); //TODO: Mensagem informativa return null; } return opener.getSocket(); } public void run() { try { socket = new Socket(host, porta); }catch(IOException e) { Log.e(Reconhecimento.LOG_VOZ, "Erro na criação do socket. " + e.getMessage()); //TODO: Mensagem informativa } } public Socket getSocket() { return socket; } } Running on the desktop Java: import java.io.BufferedReader; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.net.ServerSocket; import java.net.Socket; public class ServidorArquivo { private static int porta = 5158; static String ARQUIVO = "voz.amr"; /** * Caminho que será gravado o arquivo de audio */ static String PATH = "/home/iade/Trabalho/lib/"; public static void main(String[] args) { int i = 1; try { System.out.println("Iniciando o Servidor Socket - Android."); ServerSocket s = new ServerSocket(porta); System.out.println("Servidor Iniciado com Sucesso..."); System.out.println("Aguardando conexões na porta: " + porta); while(true) { Socket recebendo = s.accept(); System.out.println("Aceitando conexão de nº " + i); new ThreadedHandler(recebendo).start(); i++; } } catch (Exception e) { System.out.println("Erro: " + e.getMessage()); e.printStackTrace(); } } } class ThreadedHandler extends Thread { private Socket socket; public ThreadedHandler(Socket so) { socket = so; } public void run() { DataInputStream entrada = null; DataOutputStream arquivo = null; try { entrada = new DataInputStream(socket.getInputStream()); System.out.println("========== Iniciando a leitura dos dados via Sockets =========="); long tamanho = entrada.readLong(); System.out.println("Tamanho do vetor " + tamanho); File file = new File(ServidorArquivo.PATH + ServidorArquivo.ARQUIVO); if(!file.exists()) file.createNewFile(); arquivo = new DataOutputStream(new FileOutputStream(file)); for(int j = 0; j < tamanho; j++) { arquivo.write(entrada.readByte()); } System.out.println("========== Dados recebidos com sucesso =========="); } catch (Exception e) { System.out.println("Erro ao tratar do socket: " + e.getMessage()); e.printStackTrace(); } finally { System.out.println("**** Fechando as conexões ****"); try { entrada.close(); socket.close(); arquivo.close(); } catch (IOException e) { System.out.println("Erro ao fechar conex&#65533;es " + e.getMessage()); e.printStackTrace(); } } System.out.println("============= Fim da Gravação ==========="); // tratar o arquivo String cmd1 = "ffmpeg -i voz.amr -ab 12288 -ar 16000 voz.wav"; String cmd2 = "soundstretch voz.wav voz2.wav -tempo=100"; String dir = "/home/iade/Trabalho/lib"; File workDir = new File(dir); File f1 = new File(dir+"/voz.wav"); File f2 = new File(dir+"/voz2.wav"); f1.delete(); f2.delete(); try { executeCommand(cmd1, workDir); System.out.println("realizou cmd1"); executeCommand(cmd2, workDir); System.out.println("realizou cmd2"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private void executeCommand(String cmd1, File workDir) throws IOException, InterruptedException { String s; Process p = Runtime.getRuntime().exec(cmd1,null,workDir); int i = p.waitFor(); if (i == 0) { BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream())); // read the output from the command while ((s = stdInput.readLine()) != null) { System.out.println(s); } } else { BufferedReader stdErr = new BufferedReader(new InputStreamReader(p.getErrorStream())); // read the output from the command while ((s = stdErr.readLine()) != null) { System.out.println(s); } } } } Thanks in advance.

    Read the article

  • Scripting an automated SQLServer 2008 DR move

    - by ItsAMystery
    Hi All We use the built in logshipping in SQLServer to logship to our DR site but once in a month do a DR test which requires us to move back and forth between our Live and BAckup servers. We run multiple (30) databases on the system so manually backing up the final logs and disabling the jobs is too much work and takes too long. I though no problem, I will script it but have run into trouble with it always complaninig that the final logship is too early to apply even though I dont export the final log until putting the database into norecovery mode. Firstly, does any one no a simple and reliable way of doing this? I have lokoed at some 3rd party software (redgate sqlbackup I think it was) but that didnt make it easy in this situation either. What I want to be able to do is basically run a script (a series of stored procedures) to get me to DR and run another to get me back with no dataloss. My scripts are very simplistic at the moment but here they are: 2 servers Primary Paris Secondary ParisT The StartAgentJobAndWait is a script written by someone else (ta) and just checks the jobs have finished or quits it if it never ends. At the moment I am just using a test database called BOB2 but if I can get it working will pass in the database and job names. from PARIS: /* Disable backup job */ exec msdb..sp_update_job @job_name = 'LSBackup_BOB2', @enabled = 0 exec PARIST.msdb..sp_update_job @job_name = 'LSCopy_PARIS_BOB2', @enabled = 0 exec PARIST.msdb..sp_update_job @job_name = 'LSRestore_PARIS_BOB2', @enabled = 0 exec PARIST.master.dbo.DRStage2 ParisT DRStage2 DECLARE @RetValue varchar (10) EXEC @RetValue = StartAgentJobAndWait LSCopy_PARIS_BOB2 , 2 SELECT ReturnValue=@RetValue if @RetValue = 1 begin print 'The Copy Task completed Succesffuly' END ELSE print 'The Copy task failed, This may or may not be a problem, check restore state of database' SELECT @RetValue = 0 EXEC @RetValue = StartAgentJobAndWait LSRestore_PARIS_BOB2 , 2 SELECT ReturnValue=@RetValue if @RetValue = 1 begin print 'The Restore Task completed Succesffuly' END ELSE print 'The Copy task failed, This may or may not be a problem, check restore state of database' exec PARIS.master.dbo.DRStage3 /* Do the last logship and move it to Trumpington */ BACKUP log "BOB2" to disk='c:\drlogshipping\BOB2.bak' with compression, norecovery EXEC xp_cmdshell 'copy c:\drlogshipping \\192.168.7.11\drlogshipping' EXEC PARIST.master.dbo.DRTransferFinish AS BEGIN restore database "BOB2" from disk='c:\drlogshipping\bob2.bak' with recovery

    Read the article

  • Difference between a socket and a port

    - by cobie
    Could someone please explain quite clearly the difference between a port and a socket. I know that a port serves as a door into the network for an application process and that the application process uses a socket connection to the given port number to handle network communication but when you have multiple processes listening on a single port number, I am finding it difficult to understand the difference between the socket and the port and how they all fit together.

    Read the article

  • Preventing FIN_WAIT2 when closing socket

    - by patrickvacek
    I have a server program that connects to another program via a given socket, and in certain cases I need to close the connection and almost immediately re-open it on the same socket. This by and large works, except that I have to wait exactly one minute for the socket to reset. In the meantime, netstat indicates that the server sees the socket in FIN_WAIT2 and the client sees it as CLOSE_WAIT. I'm already using SO_REUSEADDR, which I thought would prevent the wait, but that isn't doing the trick. Setting SO_LINGER to zero also does not help. What else can I do to resolve this? Here are the relevant code snippets: SetUpSocket() { // Set up the socket and listen for a connection from the exelerate client. // Open a TCP/IP socket. m_baseSock = socket(PF_INET, SOCK_STREAM, IPPROTO_IP); if (m_baseSock < 0) { return XERROR; } // Set the socket options to reuse local addresses. int flag = 1; if (setsockopt(m_baseSock, SOL_SOCKET, SO_REUSEADDR, &flag, sizeof(flag)) == -1) { return XERROR; } // Set the socket options to prevent lingering after closing the socket. //~ linger li = {1,0}; //~ if (setsockopt(m_baseSock, SOL_SOCKET, SO_LINGER, &li, sizeof(li)) == -1) //~ { //~ return XERROR; //~ } // Bind the socket to the address of the current host and our given port. struct sockaddr_in addr; memset(&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_addr.s_addr = INADDR_ANY; addr.sin_port = htons(m_port); if (bind(m_baseSock, (struct sockaddr*)&addr, sizeof(addr)) != 0) { return XERROR; } // Tell the socket to listen for a connection from client. if (listen(m_baseSock, 4) != 0) { return XERROR; } return XSUCCESS; } ConnectSocket() { // Add the socket to a file descriptor set. fd_set readfds; FD_ZERO(&readfds); FD_SET(m_baseSock, &readfds); // Set timeout to ten seconds. Plenty of time. struct timeval timeout; timeout.tv_sec = 10; timeout.tv_usec = 0; // Check to see if the socket is ready for reading. int numReady = select(m_baseSock + 1, &readfds, NULL, NULL, &timeout); if (numReady > 0) { int flags = fcntl(m_baseSock, F_GETFL, 0); fcntl(m_baseSock, flags | O_NONBLOCK, 1); // Wait for a connection attempt from the client. Do not block - we shouldn't // need to since we just selected. m_connectedSock = accept(m_baseSock, NULL, NULL); if (m_connectedSock > 0) { m_failedSend = false; m_logout = false; // Spawn a thread to accept commands from client. CreateThread(&m_controlThread, ControlThread, (void *)&m_connectedSock); return XSUCCESS; } } return XERROR; } ControlThread(void *arg) { // Get the socket from the argument. socket sock = *((socket*)arg); while (true) { // Add the socket to a file descriptor set. fd_set readfds; FD_ZERO(&readfds); FD_SET(sock, &readfds); // Set timeout to ten seconds. Plenty of time. struct timeval timeout; timeout.tv_sec = 10; timeout.tv_usec = 0; // Check if there is any readable data on the socket. int num_ready = select(sock + 1, &readfds, NULL, NULL, &timeout); if (num_ready < 0) { return NULL; } // If there is data, read it. else if (num_ready > 0) { // Check the read buffer. xuint8 buf[128]; ssize_t size_read = recv(sock, buf, sizeof(buf)); if (size_read > 0) { // Get the message out of the buffer. char msg = *buf; if (msg == CONNECTED) { // Do some things... } // If we get the log-out message, log out. else if (msg == LOGOUT) { return NULL; } } } } // while return NULL; } ~Server() { // Close the sockets. if (m_baseSock != SOCKET_ERROR) { close(m_baseSock); m_baseSock = SOCKET_ERROR; } if (m_connectedSock != SOCKET_ERROR) { close(m_connectedSock); m_connectedSock = SOCKET_ERROR; } } SOCKET_ERROR is equal to -1. The server object gets destroyed, at which point the connection should close, and then recreated, at which point the SetUpSocket() and ConnectSocket() routines are called. So why do I have to wait a minute for the socket to clear? Any ideas would be appreaciated.

    Read the article

  • Socket connection to a telnet-based server hangs on read

    - by mixwhit
    I'm trying to write a simple socket-based client in Python that will connect to a telnet server. I can test the server by telnetting to its port (5007), and entering text. It responds with a NAK (error) or an AK (success), sometimes accompanied by other text. Seems very simple. I wrote a client to connect and communicate with the server, but it hangs on the first attempt to read the response. The connection is successful. Queries like getsockname and getpeername are successful. The send command returns a value that equals the number of characters I'm sending, so it seems to be sending correctly. But in the end, it always hangs when I try to read the response. I've tried using both file-based objects like readline and write (via socket.makefile), as well as using send and recv. With the file object I tried making it with "rw" and reading and writing via that object, and later tried one object for "r" and another for "w" to separate them. None of these worked. I used a packet sniffer to watch what's going on. I'm not versed in all that I'm seeing, but during a telnet session I can see my typed text and the server's text coming back. During my Python socket connection, I can see my text going to the server, but packets back don't seem to have any text in them. Any ideas on what I'm doing wrong, or any strategies to try? Here's the code I'm using (in this case, it's with send and recv): #!/usr/bin/python host = "localhost" port = 5007 msg = "HELLO EMC 1 1" msg2 = "HELLO" import socket import sys try: skt = socket.socket(socket.AF_INET, socket.SOCK_STREAM) except socket.error, e: print("Error creating socket: %s" % e) sys.exit(1) try: skt.connect((host,port)) except socket.gaierror, e: print("Address-related error connecting to server: %s" % e) sys.exit(1) except socket.error, e: print("Error connecting to socket: %s" % e) sys.exit(1) try: print(skt.send(msg)) print("SEND: %s" % msg) except socket.error, e: print("Error sending data: %s" % e) sys.exit(1) while 1: try: buf = skt.recv(1024) print("RECV: %s" % buf) except socket.error, e: print("Error receiving data: %s" % e) sys.exit(1) if not len(buf): break sys.stdout.write(buf)

    Read the article

  • Need to increase nginx throughput to an upstream unix socket -- linux kernel tuning?

    - by Ben Lee
    I am running an nginx server that acts as a proxy to an upstream unix socket, like this: upstream app_server { server unix:/tmp/app.sock fail_timeout=0; } server { listen ###.###.###.###; server_name whatever.server; root /web/root; try_files $uri @app; location @app { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header Host $http_host; proxy_redirect off; proxy_pass http://app_server; } } Some app server processes, in turn, pull requests off /tmp/app.sock as they become available. The particular app server in use here is Unicorn, but I don't think that's relevant to this question. The issue is, it just seems that past a certain amount of load, nginx can't get requests through the socket at a fast enough rate. It doesn't matter how many app server processes I set up, it doesn't even matter what the app is (tried it with a dummy app with just a single endpoint that returned an empty page with status 404). The bottleneck seems to be the socket, not the app. I'm getting a flood of these messages in the nginx error log: connect() to unix:/tmp/app.sock failed (11: Resource temporarily unavailable) while connecting to upstream Many requests result in status code 502, and those that don't take a long time to complete. The nginx write queue stat hovers around 1000. Anyway, I feel like I'm missing something obvious here, because this particular configuration of nginx and app server is pretty common, especially with Unicorn (it's the recommended method in fact). Are there any linux kernel options that needs to be set, or something in nginx? Any ideas about how to increase the throughput to the upstream socket? Something that I'm clearly doing wrong? Additional information on the environment: $ uname -a Linux app1 3.2.0-24-generic #39-Ubuntu SMP Mon May 21 16:52:17 UTC 2012 x86_64 x86_64 x86_64 GNU/Linux $ ruby -v ruby 1.9.3p194 (2012-04-20 revision 35410) [x86_64-linux] $ unicorn -v unicorn v4.3.1 $ nginx -V nginx version: nginx/1.2.1 built by gcc 4.6.3 (Ubuntu/Linaro 4.6.3-1ubuntu5) TLS SNI support enabled Current kernel tweaks: net.core.rmem_default = 65536 net.core.wmem_default = 65536 net.core.rmem_max = 16777216 net.core.wmem_max = 16777216 net.ipv4.tcp_rmem = 4096 87380 16777216 net.ipv4.tcp_wmem = 4096 65536 16777216 net.ipv4.tcp_mem = 16777216 16777216 16777216 net.ipv4.tcp_window_scaling = 1 net.ipv4.route.flush = 1 net.ipv4.tcp_no_metrics_save = 1 net.ipv4.tcp_moderate_rcvbuf = 1 net.core.somaxconn = 8192 net.netfilter.nf_conntrack_max = 131072

    Read the article

  • Multiple sendto() using UDP socket

    - by ereOn
    Hi, I have a network software which uses UDP to communicate with other instances of the same program. For different reasons, I must use UDP here. I recently had problems sending huge ammounts of data over UDP and had to implement a fragmentation system to split my messages into small data chunks. So far, it worked well but I now encounter an issue when I have to send a lot of data chunks. I have the following algorithm: Split message into small data chunks (around 1500 bytes) Iterate over the data chunks list and for each, send it using sendto() However, when I send a lot of data chunks, the receiver only gets the first 6 messages. Sometimes it misses the sixth and receives the seventh. It depends. Anyway, sendto() always indicates success. This always happen when I test my software over a loopback interface (127.0.0.1) but never over my LAN network. If I add something like std::cout << "test" << std::endl; between the sendto() then every frame is received. I am aware that UDP allows packet loss and that my frames might be loss for a lot of reasons and I suppose it has to do with the rate I am sending the data chunks at. What would be the right approach here ? Implementing some acknowledgement mechanism (just like TCP) seems overkill. Adding some arbitrary waiting time between the sendto() is ugly and will probably decrease performance. Increasing (if possible) the receiver UDP internal buffer ? I don't even know if this is possible. Something else ? I really need your advices here. Thank very much.

    Read the article

  • NNTP & Socket - How to interrupt?

    - by Cosmo
    Hi. I'm sending a message to a NNTP server in order to fetch an article's body. I don't want to wait for the answer to complete, cause I only need the first 3 lines from the body. How can I interrupt the transfer and move on to the next article? Now when I request another's article message body, I still get data from the previous one. The only way that worked for me, was to close the stream and reopen it. In my opinion this is a little bit hardcore, cause I have to login to the server every time I need a new file. Any help would be appreciated. Kind Regards.

    Read the article

  • What is stopping data flow with .NET 3.5 asynchronous System.Net.Sockets.Socket?

    - by TonyG
    I have a .NET 3.5 client/server socket interface using the asynchronous methods. The client connects to the server and the connection should remain open until the app terminates. The protocol consists of the following pattern: send stx receive ack send data1 receive ack send data2 (repeat 5-6 while more data) receive ack send etx So a single transaction with two datablocks as above would consist of 4 sends from the client. After sending etx the client simply waits for more data to send out, then begins the next transmission with stx. I do not want to break the connection between individual exchanges or after each stx/data/etx payload. Right now, after connection, the client can send the first stx, and get a single ack, but I can't put more data onto the wire after that. Neither side disconnects, the socket is still intact. The client code is seriously abbreviated as follows - I'm following the pattern commonly available in online code samples. private void SendReceive(string data) { // ... SocketAsyncEventArgs completeArgs; completeArgs.Completed += new EventHandler<SocketAsyncEventArgs>(OnSend); clientSocket.SendAsync(completeArgs); // two AutoResetEvents, one for send, one for receive if ( !AutoResetEvent.WaitAll(autoSendReceiveEvents , -1) ) Log("failed"); else Log("success"); // ... } private void OnSend( object sender , SocketAsyncEventArgs e ) { // ... Socket s = e.UserToken as Socket; byte[] receiveBuffer = new byte[ 4096 ]; e.SetBuffer(receiveBuffer , 0 , receiveBuffer.Length); e.Completed += new EventHandler<SocketAsyncEventArgs>(OnReceive); s.ReceiveAsync(e); // ... } private void OnReceive( object sender , SocketAsyncEventArgs e ) {} // ... if ( e.BytesTransferred > 0 ) { Int32 bytesTransferred = e.BytesTransferred; String received = Encoding.ASCII.GetString(e.Buffer , e.Offset , bytesTransferred); dataReceived += received; } autoSendReceiveEvents[ SendOperation ].Set(); // could be moved elsewhere autoSendReceiveEvents[ ReceiveOperation ].Set(); // releases mutexes } The code on the server is very similar except that it receives first and then sends a response - the server is not doing anything (that I can tell) to modify the connection after it sends a response. The problem is that the second time I hit SendReceive in the client, the connection is already in a weird state. Do I need to do something in the client to preserve the SocketAsyncEventArgs, and re-use the same object for the lifetime of the socket/connection? I'm not sure which eventargs object should hang around during the life of the connection or a given exchange. Do I need to do something, or Not do something in the server to ensure it continues to Receive data? The server setup and response processing looks like this: void Start() { // ... listenSocket.Bind(...); listenSocket.Listen(0); StartAccept(null); // note accept as soon as we start. OK? mutex.WaitOne(); } void StartAccept(SocketAsyncEventArgs acceptEventArg) { if ( acceptEventArg == null ) { acceptEventArg = new SocketAsyncEventArgs(); acceptEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(OnAcceptCompleted); } Boolean willRaiseEvent = this.listenSocket.AcceptAsync(acceptEventArg); if ( !willRaiseEvent ) ProcessAccept(acceptEventArg); // ... } private void OnAcceptCompleted( object sender , SocketAsyncEventArgs e ) { ProcessAccept(e); } private void ProcessAccept( SocketAsyncEventArgs e ) { // ... SocketAsyncEventArgs readEventArgs = new SocketAsyncEventArgs(); readEventArgs.SetBuffer(dataBuffer , 0 , Int16.MaxValue); readEventArgs.Completed += new EventHandler<SocketAsyncEventArgs>(OnIOCompleted); readEventArgs.UserToken = e.AcceptSocket; dataReceived = ""; // note server is degraded for single client/thread use // As soon as the client is connected, post a receive to the connection. Boolean willRaiseEvent = e.AcceptSocket.ReceiveAsync(readEventArgs); if ( !willRaiseEvent ) this.ProcessReceive(readEventArgs); // Accept the next connection request. this.StartAccept(e); } private void OnIOCompleted( object sender , SocketAsyncEventArgs e ) { // switch ( e.LastOperation ) case SocketAsyncOperation.Receive: ProcessReceive(e); // similar to client code // operate on dataReceived here case SocketAsyncOperation.Send: ProcessSend(e); // similar to client code } // execute this when a data has been processed into a response (ack, etc) private SendResponseToClient(string response) { // create buffer with response // currentEventArgs has class scope and is re-used currentEventArgs.SetBuffer(sendBuffer , 0 , sendBuffer.Length); Boolean willRaiseEvent = currentClient.SendAsync(currentEventArgs); if ( !willRaiseEvent ) ProcessSend(currentEventArgs); } A .NET trace shows the following when sending ABC\r\n: Socket#7588182::SendAsync() Socket#7588182::SendAsync(True#1) Data from Socket#7588182::FinishOperation(SendAsync) 00000000 : 41 42 43 0D 0A Socket#7588182::ReceiveAsync() Exiting Socket#7588182::ReceiveAsync() - True#1 And it stops there. It looks just like the first send from the client but the server shows no activity. I think that could be info overload for now but I'll be happy to provide more details as required. Thanks!

    Read the article

  • Socket Select with empty fd set

    - by whoi
    Hi; Suppose you have an fd set which can have zero or more sockets in it. When I try to call select operation on empty fd set, what I get is -1 as the number of fds which are set, meaning error. So what would you suggest to overcome this problem, you might say do not call if empty but I have a loop and any time fd set can hold 0 or more sockets. What is the best approach about this problem? (we are on C programming language)

    Read the article

  • Java Socket Disconnect Reporting vs. C# Disconnection

    - by ikurtz
    in C# when a sockets connection is terminated the other node is informed of this before terminating the link thus the remaning node can update the connection status. in Java when i terminate a communication link the other node keeps reporting the connection as valid. do i need to implement a read cycle (makes sense) that reports the connection as lost when it recieves a -1 during read (in C# this is 0 i think)? thank you for your insight. EDIT: thanks to you both. as i suspected and mentioned in my post that an additional check is required to confirm the connected state of a connection.

    Read the article

  • The behavior of send() and recv() in socket communication

    - by gc
    The following is the setup: Server Client | | accept connect | | v | send msg1- | | | v v recv <- send | | v v send msg2- recv | | v v close Here is my question: 1. Client actually receives msg1 before it closes, why is it like this? 2. send msg2 returns normally. Since client closes after receiving msg1, why is send msg2 successful?

    Read the article

  • a problem in socket programing in perl

    - by isu
    I write this code : #!/usr/local/bin/perl use strict; use LWP::UserAgent; my $ua = new LWP::UserAgent(agent => 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.5) Gecko/20060719 Firefox/1.5.0.5'); $ua->proxy([qw(http https)] => 'http://203.185.28.228:1080' #that is just socks:port); my $response = $ua->get("http://www.google.com"); print $response->code,' ', $response->message,"\n"; but when i execute it i get this error: 500 Can't connect to 203.185.28.228:1080 (connect: timeout) what am i going to do ?

    Read the article

< Previous Page | 4 5 6 7 8 9 10 11 12 13 14 15  | Next Page >