Search Results

Search found 3040 results on 122 pages for 'socket'.

Page 11/122 | < Previous Page | 7 8 9 10 11 12 13 14 15 16 17 18  | Next Page >

  • How to develop a client-server seat booking program via java socket programming ?

    - by Haxed
    I have a project to develop a client server application in java. This is to be done using socket programming. Our lecturer, used 2 files, the TCPClient.java and TCPServer.java, to make a connection and we typed "Hi" in the client and the server displayed that message. I need to develop a seat booking application. Any suggestions for tutorials or tips or a book perhaps would be nice. Many Thanks

    Read the article

  • Socket.io - Tutorials? Better docs?

    - by mattbasta
    I've been toying around with nodejs for some of my COMET stuff and stumbled across Socket.io. Unfortunately, the documentation is fairly lacking and there is only one "real" example. Is anyone familiar with some decent tutorials on some of the intricacies of this library? Maybe just some better docs? I'd really like to use it, but I'm probably going to avoid it if I can't figure how to use it properly.

    Read the article

  • Is there a way to close a Unix socket for only reading or writing?

    - by Sii
    Is there a way to only close "one end" of a TCP socket to cleanly indicate one side of a connection is done writing to the connection? (Just like you do with a pipe in every Unix pipe tutorial ever.) Or should I use some in-band solution like a sentinel value or some such? I only found shutdown() in the libc documentation and that doesn't seem like it does what I want.

    Read the article

  • Perl not closing TCP sockets if clients are no longer connected?

    - by LM
    The purpose of the application is to listen for a specific UDP multicast and then to forward the data to any TCP clients connected to the server. The code works fine, but I have a problem with the sockets not closing after the TCP clients disconnects. A socketsniffer utility shows the the sockets remain open and all the UDP data continues to be forwarded to the clients. The problem I believe is with the "if ($write-connected())" block as it always return true, even if the TCP client is no longer connected. I use standard Windows Telnet to connect to the server and to see the data. When I close telnet, the TCP socket is suppose to close on the server. Any reason why connected() show the connections as active even if they are not? Also, what alternative should I use then? Code: #!/usr/bin/perl use IO::Socket::Multicast; use IO::Socket; use IO::Select; my $tcp_port = "4550"; my $tcp_socket = IO::Socket::INET->new( Listen => SOMAXCONN, LocalAddr => '0.0.0.0', LocalPort => $tcp_port, Proto => 'tcp', ReuseAddr => 1, ); use Socket qw(IPPROTO_TCP TCP_NODELAY); setsockopt( $tcp_socket, IPPROTO_TCP, TCP_NODELAY, 1); use constant GROUP => '239.2.0.81'; use constant PORT => '6550'; my $udp_socket= IO::Socket::Multicast->new(Proto=>'udp',LocalPort=>PORT); $udp_socket->mcast_add(GROUP) || die "Couldn't set group: $!\n"; my $read_select = IO::Select->new(); my $write_select = IO::Select->new(); $read_select->add($tcp_socket); $read_select->add($udp_socket); ## Loop forever, reading data from the UDP socket and writing it to the ## TCP socket(s). while (1) { ## No timeout specified (see docs for IO::Select). This will block until a TCP ## client connects or we have data. my @read = $read_select->can_read(); foreach my $read (@read) { if ($read == $tcp_socket) { ## Handle connect from TCP client. Note that UDP connections are ## stateless (no accept necessary)... my $new_tcp = $read->accept(); $write_select->add($new_tcp); } elsif ($read == $udp_socket) { ## Handle data received from UDP socket... my $recv_buffer; $udp_socket->recv($recv_buffer, 1024, undef); ## Write the data read from UDP out to the TCP client(s). Again, no ## timeout. This will block until a TCP socket is writable. my @write = $write_select->can_write(); foreach my $write (@write) { ## Make sure the socket is still connected before writing. if ($write->connected()) { $write->send($recv_buffer); } else { $write_select->remove($write); close $write; } } } } }

    Read the article

  • could not bind socket while haproxy restart

    - by shreyas
    I m restarting HAproxy by following command haproxy -f /etc/haproxy/haproxy.cfg -p /var/run/haproxy.pid -sf $(cat /var/run/haproxy.pid) but i get following message [ALERT] 183/225022 (9278) : Starting proxy appli1-rewrite: cannot bind socket [ALERT] 183/225022 (9278) : Starting proxy appli2-insert: cannot bind socket [ALERT] 183/225022 (9278) : Starting proxy appli3-relais: cannot bind socket [ALERT] 183/225022 (9278) : Starting proxy appli4-backup: cannot bind socket [ALERT] 183/225022 (9278) : Starting proxy ssl-relay: cannot bind socket [ALERT] 183/225022 (9278) : Starting proxy appli5-backup: cannot bind socket my haproxy.cfg file looks likefollowing global log 127.0.0.1 local0 log 127.0.0.1 local1 notice #log loghost local0 info maxconn 4096 #chroot /usr/share/haproxy user haproxy group haproxy daemon #debug #quiet defaults log global mode http option httplog option dontlognull retries 3 option redispatch maxconn 2000 contimeout 5000 clitimeout 50000 srvtimeout 50000 listen appli1-rewrite 0.0.0.0:10001 cookie SERVERID rewrite balance roundrobin server app1_1 192.168.34.23:8080 cookie app1inst1 check inter 2000 rise 2 fall 5 server app1_2 192.168.34.32:8080 cookie app1inst2 check inter 2000 rise 2 fall 5 server app1_3 192.168.34.27:8080 cookie app1inst3 check inter 2000 rise 2 fall 5 server app1_4 192.168.34.42:8080 cookie app1inst4 check inter 2000 rise 2 fall 5 listen appli2-insert 0.0.0.0:10002 option httpchk balance roundrobin cookie SERVERID insert indirect nocache server inst1 192.168.114.56:80 cookie server01 check inter 2000 fall 3 server inst2 192.168.114.56:81 cookie server02 check inter 2000 fall 3 capture cookie vgnvisitor= len 32 option httpclose # disable keep-alive rspidel ^Set-cookie:\ IP= # do not let this cookie tell our internal IP address listen appli3-relais 0.0.0.0:10003 dispatch 192.168.135.17:80 listen appli4-backup 0.0.0.0:10004 option httpchk /index.html option persist balance roundrobin server inst1 192.168.114.56:80 check inter 2000 fall 3 server inst2 192.168.114.56:81 check inter 2000 fall 3 backup listen ssl-relay 0.0.0.0:8443 option ssl-hello-chk balance source server inst1 192.168.110.56:443 check inter 2000 fall 3 server inst2 192.168.110.57:443 check inter 2000 fall 3 server back1 192.168.120.58:443 backup listen appli5-backup 0.0.0.0:10005 option httpchk * balance roundrobin cookie SERVERID insert indirect nocache server inst1 192.168.114.56:80 cookie server01 check inter 2000 fall 3 server inst2 192.168.114.56:81 cookie server02 check inter 2000 fall 3 server inst3 192.168.114.57:80 backup check inter 2000 fall 3 capture cookie ASPSESSION len 32 srvtimeout 20000 option httpclose # disable keep-alive option checkcache # block response if set-cookie & cacheable rspidel ^Set-cookie:\ IP= # do not let this cookie tell our internal IP address #errorloc 502 http://192.168.114.58/error502.html #errorfile 503 /etc/haproxy/errors/503.http errorfile 400 /etc/haproxy/errors/400.http errorfile 403 /etc/haproxy/errors/403.http errorfile 408 /etc/haproxy/errors/408.http errorfile 500 /etc/haproxy/errors/500.http errorfile 502 /etc/haproxy/errors/502.http errorfile 503 /etc/haproxy/errors/503.http errorfile 504 /etc/haproxy/errors/504.http what is wrong with my aproach

    Read the article

  • Socket server with multiple clients, sending messages to many clients without hurting liveliness

    - by Karl Johanson
    I have a small socket server, and I need to distribute various messages from client-to-client depending on different conditionals. However I think I have a small problem with livelyness in my current code, and is there anything wrong in my approach: public class CuClient extends Thread { Socket socket = null; ObjectOutputStream out; ObjectInputStream in; CuGroup group; public CuClient(Socket s, CuGroup g) { this.socket = s; this.group = g; out = new ObjectOutputStream(this.socket.getOutputStream()); out.flush(); in = new ObjectInputStream(this.socket.getInputStream()); } @Override public void run() { String cmd = ""; try { while (!cmd.equals("client shutdown")) { cmd = (String) in.readObject(); this.group.broadcastToGroup(this, cmd); } out.close(); in.close(); socket.close(); } catch (Exception e) { System.out.println(this.getName()); e.printStackTrace(); } } public void sendToClient(String msg) { try { this.out.writeObject(msg); this.out.flush(); } catch (IOException ex) { } } And my CuGroup: public class CuGroup { private Vector<CuClient> clients = new Vector<CuClient>(); public void addClient(CuClient c) { this.clients.add(c); } void broadcastToGroup(CuClient clientName, String cmd) { Iterator it = this.clients.iterator(); while (it.hasNext()) { CuClient cu = (CuClient)it.next(); cu.sendToClient(cmd); } } } And my main-class: public class SmallServer { public static final Vector<CuClient> clients = new Vector<CuClient>(10); public static boolean serverRunning = true; private ServerSocket serverSocket; private CuGroup group = new CuGroup(); public void body() { try { this.serverSocket = new ServerSocket(1337, 20); System.out.println("Waiting for clients\n"); do { Socket s = this.serverSocket.accept(); CuClient t = new CuClient(s,group); System.out.println("SERVER: " + s.getInetAddress() + " is connected!\n"); t.start(); } while (this.serverRunning); } catch (IOException ex) { ex.printStackTrace(); } } public static void main(String[] args) { System.out.println("Server"); SmallServer server = new SmallServer(); server.body(); } } Consider the example with many more groups, maybe a Collection of groups. If they all synchronize on a single Object, I don't think my server will be very fast. I there a pattern or something that can help my liveliness?

    Read the article

  • Async Socket Listener on separate thread - VB.net

    - by TheHockeyGeek
    I am trying to use the code from Microsoft for an Async Socket connection. It appears the listener runs in the main thread locking the GUI. I am new at both socket connections and multi-threading all at the same time. Having a hard time getting my mind wrapped around this all at once. The code used is at http://msdn.microsoft.com/en-us/library/fx6588te.aspx Using this example, how can I move the listener to its own thread? Public Shared Sub Main() ' Data buffer for incoming data. Dim bytes() As Byte = New [Byte](1023) {} ' Establish the local endpoint for the socket. Dim ipHostInfo As IPHostEntry = Dns.GetHostEntry(Dns.GetHostName()) Dim ipAddress As IPAddress = ipHostInfo.AddressList(1) Dim localEndPoint As New IPEndPoint(ipAddress, 11000) ' Create a TCP/IP socket. Dim listener As New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) ' Bind the socket to the local endpoint and listen for incoming connections. listener.Bind(localEndPoint) listener.Listen(100)

    Read the article

  • Remote Socket Read In Multi-Threaded Application Returns Zero Bytes or EINTR (104)

    - by user39891
    Hi. Am a c-coder for a while now - neither a newbie nor an expert. Now, I have a certain daemoned application in C on a PPC Linux. I use PHP's socket_connect as a client to connect to this service locally. The server uses epoll for multiplexing connections via a Unix socket. A user submitted string is parsed for certain characters/words using strstr() and if found, spawns 4 joinable threads to different websites simultaneously. I use socket, connect, write and read, to interact with the said webservers via TCP on their port 80 in each thread. All connections and writes seems successful. Reads to the webserver sockets fail however, with either (A) all 3 threads seem to hang, and only one thread returns -1 and errno is set to 104. The responding thread takes like 10 minutes - an eternity long:-(. *I read somewhere that the 104 (is EINTR?), which in the network context suggests that ...'the connection was reset by peer'; or (B) 0 bytes from 3 threads, and only 1 of the 4 threads actually returns some data. Isn't the socket read/write thread-safe? I use thread-safe (and reentrant) libc functions such as strtok_r, gethostbyname_r, etc. *I doubt that the said webhosts are actually resetting the connection, because when I run a single-threaded standalone (everything else equal) all things works perfectly right, but of course in series not parallel. There's a second problem too (oops), I can't write back to the client who connect to my epoll-ed Unix socket. My daemon application will hang and hog CPU 100% for ever. Yet nothing is written to the clients end. Am sure the client (a very typical PHP socket application) hasn't closed the connection whenever this is happening - no error(s) detected either. Any ideas? I cannot figure-out whatever is wrong even with Valgrind, GDB or much logging. Kindly help where you can.

    Read the article

  • python sending incomplete data over socket

    - by tipu
    I have this socket server script, import SocketServer import shelve import zlib class MyTCPHandler(SocketServer.BaseRequestHandler): def handle(self): self.words = shelve.open('/home/tipu/Dropbox/dev/workspace/search/words.db', 'r'); self.tweets = shelve.open('/home/tipu/Dropbox/dev/workspace/search/tweets.db', 'r'); param = self.request.recv(1024).strip() try: result = str(self.words[param]) except KeyError: result = "set()" self.request.send(str(result)) if __name__ == "__main__": HOST, PORT = "localhost", 50007 SocketServer.TCPServer.allow_reuse_address = True server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler) server.serve_forever() And this receiver, from django.http import HttpResponse from django.template import Context, loader import shelve import zlib import socket def index(req, param = ''): HOST = 'localhost' PORT = 50007 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((HOST, PORT)) s.send(param) data = zlib.decompress(s.recv(131072)) s.close() print 'Received', repr(data) t = loader.get_template('index.html') c = Context({ 'foo' : data }) return HttpResponse(t.render(c)) I am sending strings to the receiver that are in the hundreds of kilobytes. I end up only receiving a portion of it. Is there a way that I can fix that so that the whole string is sent?

    Read the article

  • socket.error: [Errno 10054]

    - by C0d3r
    import socket, sys if len(sys.argv) !=3 : print "Usage: ./supabot.py <host> <port>" sys.exit(1) irc = sys.argv[1] port = int(sys.argv[2]) sck = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sck.connect((irc, port)) sck.send('NICK supaBOT\r\n') sck.send('USER supaBOT supaBOT supaBOT :supaBOT Script\r\n') sck.send('JOIN #darkunderground' + '\r\n') data = '' while True: data = sck.recv(1024) if data.find('PING') != -1: sck.send('PONG ' + data.split() [1] + '\r\n') print data elif data.find('!info') != -1: sck.send('PRIVMSG #darkunderground supaBOT v1.0 by sourD' + '\r\n') print sck.recv(1024) when I run this code I get this error.. socket.error: [Errno 10054] An existing connection was forcibly closed by the remote host it says that the error is in line 16, in data = sck.recv(1024)

    Read the article

  • Programming error in Java Socket

    - by Akhil K Nambiar
    Can you tell me what is the error in this code? Socket socket = new Socket(hostname, port); PrintWriter out = new PrintWriter(socket.getOutputStream(), true); //DataInputStream is = new DataInputStream(socket.getInputStream()); out.println("hi"); System.out.print(in.readLine()); The Server Socket program is written in .Net and it echoes back the data. The data is sent successfully but could not be retrieved properly. I tried the same by using the linux command nc 192.168.1.6 8425 (enter) Hi (Sent data) Hi (recieved data) When I checked the code the data is found to have sent as byteStream in .Net. Is that a problem. In that case what modification should I make.

    Read the article

  • Is it possible to put an 8000 series socket-F Opteron into a dual-socket motherboard?

    - by René Kåbis
    Exactly what it says on the Tin. I have a dual-socket, socket-F motherboard in which I am looking to put two high-end quad-core Opterons, but the 2000 series are nearly double the price of the 8000 series on eBay. Can I just drop in a pair of 8000 series processors and be done with it, or are there processor-critical motherboard features that would be present on a quad(+)-socket motherboard that don’t exist on a dual-socket motherboard? Please elaborate or link to resources that can explain this further, as I am not adverse to research (and I am interested in the technical issues involved) I am probably using the wrong search terms, as Google failed to return anything within the first few dozen results.

    Read the article

  • Delay command execution over sockets

    - by David
    I've been trying to fix the game loop in a real time (tick delay) MUD. I realized using Thread.Sleep would seem clunky when the user spammed commands through their choice of client (Zmud, etc) e.g. east;south;southwest would wait three move ticks and then output everything from the past couple rooms. The game loop basically calls a Flush and Fill method for each socket during each tick (50ms) private void DoLoop() { Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); while (running) { // for each socket, flush and fill ConnectionMonitor.Update(); stopWatch.Stop(); WaitIfNeeded(stopWatch.ElapsedMilliseconds); stopWatch.Reset(); } } The Fill method fires the command events, but as mentioned before, they currently block using Thread.Sleep. I tried adding a "ready" flag to the state object that attempts to execute the command along with a queue of spammed commands, but it ends up executing one command and queuing up the rest i.e. each subsequent command executes something that got queued up that should've been executed before. I must be missing something about the timer. private readonly Queue<SpammedCommand> queuedCommands = new Queue<SpammedCommand>(); private bool ready = true; private void TryExecuteCommand(string input) { var commandContext = CommandContext.Create(input); var player = Server.Current.Database.Get<Player>(Session.Player.Key); var commandInfo = Server.Current.CommandLookup .FindCommand(commandContext.CommandName, player.IsAdmin); if (commandInfo != null) { if (!ready) { // queue command queuedCommands.Enqueue(new SpammedCommand() { Context = commandContext, Info = commandInfo }); return; } if (queuedCommands.Count > 0) { // queue the incoming command queuedCommands.Enqueue(new SpammedCommand() { Context = commandContext, Info = commandInfo, }); // dequeue and execute var command = queuedCommands.Dequeue(); command.Info.Command.Execute(Session, command.Context); setTimeout(command.Info.TickLength); return; } commandInfo.Command.Execute(Session, commandContext); setTimeout(commandInfo.TickLength); } else { Session.WriteLine("Command not recognized"); } } Finally, setTimeout was supposed to set the execution delay (TickLength) for that command, and makeReady just sets the ready flag on the state object to true. private void setTimeout(TickDelay tickDelay) { ready = false; var t = new System.Timers.Timer() { Interval = (long) tickDelay, AutoReset = false, }; t.Elapsed += makeReady; t.Start(); // fire this in tickDelay ms } // MAKE READYYYYY!!!! private void makeReady(object sender, System.Timers.ElapsedEventArgs e) { ready = true; } Am I missing something about the System.Timers.Timer created in setTimeout? How can I execute (and output) spammed commands per TickLength without using Thread.Sleep?

    Read the article

  • Multiple INET sockets (mulple IP's too) connected to UNIX sockets

    - by Andrew
    HOST = same host all the time, accepts multiple connection. I have a dedicated server and I will buy extra IP's. Socket 1 connects to HOST:PORT, from IP-1 Socket 2 connects to HOST:PORT, from IP-1 Socket 3 connects to HOST:PORT, from IP-1 Socket 4 connects to HOST:PORT, from IP-2 Socket 5 connects to HOST:PORT, from IP-2 Socket 6 connects to HOST:PORT, from IP-2 After creating all sockets I want to access them easy as UNIX sockets from PHP. /sys/socket1 /sys/socket2 /sys/socket3 /sys/socket4 /sys/socket5 /sys/socket6 I want the sockets to work in background (like daemon) and I want to be able to connect from PHP to any of this sockets and RECV/SEND whatever I want. I saw "socat" and I think that's the solution for me, please tell me how to use socat, or how to do it other way. Thankyou!

    Read the article

  • Transparent proxying - how to pass socket to local server without modification?

    - by Luca Farber
    Hello, I have a program that listens on port 443 and then redirects to either an SSH or HTTPS local server depending on the detected protocol. The program does this by connecting to the local server and proxying all data back and forth through its own process. However, this causes the originating host on the local servers to be logged as localhost. Is there any way to pass the socket directly to the local server process (rather than just making a new TCP connection) so that the parameters of sockaddr_in (or sockaddr_in6) will be retained? Platform for this is Linux.

    Read the article

  • Sending multiline message via sockets without closing the connection

    - by Yasir Arsanukaev
    Hello folks. Currently I have this code of my client-side Haskell application: import Network.Socket import Network.BSD import System.IO hiding (hPutStr, hPutStrLn, hGetLine, hGetContents) import System.IO.UTF8 connectserver :: HostName -- ^ Remote hostname, or localhost -> String -- ^ Port number or name -> IO Handle connectserver hostname port = withSocketsDo $ do -- withSocketsDo is required on Windows -- Look up the hostname and port. Either raises an exception -- or returns a nonempty list. First element in that list -- is supposed to be the best option. addrinfos <- getAddrInfo Nothing (Just hostname) (Just port) let serveraddr = head addrinfos -- Establish a socket for communication sock <- socket (addrFamily serveraddr) Stream defaultProtocol -- Mark the socket for keep-alive handling since it may be idle -- for long periods of time setSocketOption sock KeepAlive 1 -- Connect to server connect sock (addrAddress serveraddr) -- Make a Handle out of it for convenience h <- socketToHandle sock ReadWriteMode -- Were going to set buffering to LineBuffering and then -- explicitly call hFlush after each message, below, so that -- messages get logged immediately hSetBuffering h LineBuffering return h sendid :: Handle -> String -> IO String sendid h id = do hPutStr h id -- Make sure that we send data immediately hFlush h -- Retrieve results hGetLine h The code portions in connectserver are from this chapter of Real World Haskell book where they say: When dealing with TCP data, it's often convenient to convert a socket into a Haskell Handle. We do so here, and explicitly set the buffering – an important point for TCP communication. Next, we set up lazy reading from the socket's Handle. For each incoming line, we pass it to handle. After there is no more data – because the remote end has closed the socket – we output a message about that. Since hGetContents blocks until the server closes the socket on the other side, I used hGetLine instead. It satisfied me before I decided to implement multiline output to client. I wouldn't like the server to close a socket every time it finishes sending multiline text. The only simple idea I have at the moment is to count the number of linefeeds and stop reading lines after two subsequent linefeeds. Do you have any better suggestions? Thanks.

    Read the article

  • Where is the best place to start learning Java Socket Programming?

    - by MarcoBoomTing
    I wish to create a Java Socket server which can be connected to using Javascript and/or Flash. I have experience in Connecting to sockets in flash, and using a comet like system in Ajax. I wish to make a live communication system, which will intale multiple connections to the server from various clients, needing almost instant communication between peers. I coded a system like this in PHP but I want to convert it to Java, simply because I don't want the PHP engine to be tied up on this Sever, as it serves all the web stuff normally on the site, and i've heard is more powerful for this sort of thing. Just looking for advice on where I can start learning how to write this sort of system using Java? I have previous coding experience in PHP, Javascript, Adobe Air and AS3 if That helps?

    Read the article

  • What to choose API based server or Socket based server for data driven application

    - by Imdad
    I am working on a project which has a Desktop Application for MAC/COCOA, a native application for iPhone another native application in iPad. All the application do almost same thing. The applications are data driven applications. Every communication to server is made via a restful API developed in PHP. When a user logs in a lot of data is fetched from server. And to remain in sync with server pooling is done. As there are lot of data to pool it makes application slower and un-reliable. A possible solution that comes into my mind is to use Socket based server. My question is that will it reasonably improve the performance? And which technology (of sockets) will be good as a server side solution for data driven application? I have heard a lot about Node.js. Please give your suggestions.

    Read the article

  • Should I ditch AJAX in client side web development when I've got a web-socket open?

    - by jt0dd
    I was thinking that maybe I should forget AJAX (HTTP) requests when I've got a web-socket open between client and server, but I decided I should ask here to check if this could be a bad practice for some reason that I'm not thinking of. Once the socket is open, there's less syntax (often meaning simpler error handling) involved in passing information between client and server with Socket.io (just one example of a web-socket). Is there some obvious situation where a web-socket (Socket.io for example) isn't going to be capable of handling a functionality that an AJAX request could do easily?

    Read the article

  • place to host a simple php socket server

    - by bonusbox
    i am running a small project that occasionally requires me to run a php socket script through ssh. it uses a few bytes of bandwidth (just some text) which activates my art installation project. i tried a simple web hosting plan but that didn't support sockets, so know i am using a 32$ vps plan on namecheap.com just to run a simple php script. i don't really need to host anything else on it. i find it kind of excessive for such a simple thing. is there a place i can run my script for a lower cost? any servers that support php sockets and ssh?

    Read the article

  • Python Socket Getting Connection Reset

    - by Ian
    I created a threaded socket listener that stores newly accepted connections in a queue. The socket threads then read from the queue and respond. For some reason, when doing benchmarking with 'ab' (apache benchmark) using a concurrency of 2 or more, I always get a connection reset before it's able to complete the benchmark (this is taking place locally, so there's no external connection issue). class server: _ip = '' _port = 8888 def __init__(self, ip=None, port=None): if ip is not None: self._ip = ip if port is not None: self._port = port self.server_listener(self._ip, self._port) def now(self): return time.ctime(time.time()) def http_responder(self, conn, addr): httpobj = http_builder() httpobj.header('HTTP/1.1 200 OK') httpobj.header('Content-Type: text/html; charset=UTF-8') httpobj.header('Connection: close') httpobj.body("Everything looks good") data = httpobj.generate() sent = conn.sendall(data) def http_thread(self, id): self.log("THREAD %d: Starting Up..." % id) while True: conn, addr = self.q.get() ip, port = addr self.log("THREAD %d: responding to request: %s:%s - %s" % (id, ip, port, self.now())) self.http_responder(conn, addr) self.q.task_done() conn.close() def server_listener(self, host, port): self.q = Queue.Queue(0) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.bind( (host, port) ) sock.listen(5) for i in xrange(4): #thread count thread.start_new(self.http_thread, (i+1, )) while True: self.q.put(sock.accept()) sock.close() server('', 9999) When running the benchmark, I get totally random numbers of good requests before it errors out, usually between 4 and 500. Edit: Took me a while to figure it out, but the problem was in sock.listen(5). Because I was using apache benchmark with a higher concurrency (5 and up) it was causing the backlog of connections to pile up, at which point the connections started getting dropped by the socket.

    Read the article

  • How does the socket API accept() function work?

    - by Eli Bendersky
    The socket API is the de-facto standard for TCP/IP and UDP/IP communications (that is, networking code as we know it). However, one of its core functions, accept() is a bit magical. To borrow a semi-formal definition: accept() is used on the server side. It accepts a received incoming attempt to create a new TCP connection from the remote client, and creates a new socket associated with the socket address pair of this connection. In other words, accept returns a new socket through which the server can communicate with the newly connected client. The old socket (on which accept was called) stays open, on the same port, listening for new connections. How does accept work? How is it implemented? There's a lot of confusion on this topic. Many people claim accept opens a new port and you communicate with the client through it. But this obviously isn't true, as no new port is opened. You actually can communicate through the same port with different clients, but how? When several threads call recv on the same port, how does the data know where to go? I guess it's something along the lines of the client's address being associated with a socket descriptor, and whenever data comes through recv it's routed to the correct socket, but I'm not sure. It'd be great to get a thorough explanation of the inner-workings of this mechanism.

    Read the article

  • Threading in client-server socket program - proxy sever

    - by crazyTechie
    I am trying to write a program that acts as a proxy server. Proxy server basically listens to a given port (7575) and sends the request to the server. As of now, I did not implement caching the response. The code looks like ServerSocket socket = new ServerSocket(7575); Socket clientSocket = socket.accept(); clientRequestHandler(clientSocket); I changed the above code as below: //calling the same clientRequestHandler method from inside another method. Socket clientSocket = socket.accept(); Thread serverThread = new Thread(new ConnectionHandler(client)); serverThread.start(); class ConnectionHandler implements Runnable { Socket clientSocket = null; ConnectionHandler(Socket client){ this.clientSocket = client; } @Override public void run () { try { PrxyServer.clientRequestHandler(clientSocket); } catch (Exception ex) { ex.printStackTrace(); } } } Using the code, I am able to open a webpage like google. However, if I open another web page even I completely receive the first response, I get connection reset by peer expection. 1. How can I handle this issue Can i use threading to handle different requests. Can someone give a reference where I look for example code that implements threading. Thanks. Thanks.

    Read the article

  • Sending arbitrarily long string over Java TCP socket

    - by bibismcbryde
    I have an Android app that communicates over a TCP socket with a server I wrote. The method I'm using now to read and write output works fine for smaller strings (up to 60kB) but I get an exception thrown when the string is much longer than that. Here is the relevant part of what I have for the server and client: Server: DataInputStream dis = null; DataOutputStream dos = null; try { dis = new DataInputStream(server.getInputStream()); dos = new DataOutputStream(server.getOutputStream()); String input = ""; input = dis.readUTF(); handle_input info = new handle_input(input, id); String xml = info.handle(); dos.writeUTF(xml); server.close(); } Client: Socket socket = null; DataOutputStream dos = null; DataInputStream dis = null; Boolean result; try { socket = new Socket(ip, port); dos = new DataOutputStream(socket.getOutputStream()); dis = new DataInputStream(socket.getInputStream()); dos.writeUTF(the_text); String in = ""; while (in.equals("")) { in += dis.readUTF(); } } How can I modify it to deal with potentially enormous Strings? I've been looking around and can't seem to find a clear answer. Thanks.

    Read the article

  • How to handle corrupt messages arriving on a socket?

    - by Pieter
    I've got a working socket handling mechanism, similar (but a bit more complex) to Qt's Fortune Example http://qt.nokia.com/doc/4.5/network-fortuneclient.html http://qt.nokia.com/doc/4.5/network-fortuneserver.html Now I'm wondering how to handle corrupt messages. Discarding the data is a start, but I need to discard up to a point I can start processing messages again. The corrupt message may be lost, but I need to be able to recover from it. I've got the following idea in mind: Put a fixed header at the start of each message, eg. 0xABCDEF01. When recovering, lookup this header and restart handling incoming messages. = Break off readFortune() on a timeout and recover = When encountering an inconsistent header, recover A huge blocksize is still going to be a problem. To fix that, I should be constantly checking whether or not I'm reading gibberish, but this is not always possible. I can also limit the blocksize on certain message-types. Any ideas on this? Any proposals on what to use as byteword?

    Read the article

< Previous Page | 7 8 9 10 11 12 13 14 15 16 17 18  | Next Page >