Write A Socket Program For Echo%2fping%2ftalk Commands In Java

Home > Articles > Programming > Java

  1. Write A Socket Program For Echo 2fping 2ftalk Commands In Javascript
  2. Write A Socket Program For Echo 2fping 2ftalk Commands In Java Runtime
  3. Write A Socket Program For Echo 2fping 2ftalk Commands In Java Compiler
  4. Write A Socket Program For Echo 2fping 2ftalk Commands In Java Programming
  1. A Server Socket in Java
< BackPage 4 of 11Next >

The EchoClient example creates a socket, thereby getting a connection to the echo server. It reads input from the user on the standard input stream, and then forwards that text to the echo server by writing the text to the socket. The server echoes the input back through the socket to the client. Type the following command to run the server program: java QuoteServer Quotes.txt 17 And run the client program (on the same computer): java QuoteClient localhost 17 Both the client and server are running in an infinite loop, so you have to press Ctrl + C to terminate. EchoServer and EchoClient Commuincation Program using Java, Network Lab Programs Anna University, Network Lab Programs in Java, Computer Networks Lab Programs Download, Networking Lab Programs for M.E, Computer Networks Lab Programs in C, Computer Networks Lab Programs for IT, Anna University Practical Lab Manuals for Engineering Students, Java Programs with Explanation, Source Code in Java. Java Socket Server Example #3: Reverse Server (multi-threaded) Modify the server’s code to handle each socket client in a new thread like this: import java.io.; import java.net.; /. This program demonstrates a simple TCP/IP socket server that echoes every. message from the client in reversed form. This server is multi-threaded. UDP Echo Client: UDP Client « Network « Java Tutorial. Home; Java Tutorial. Private DatagramSocket socket; private boolean stopped = false. A simple Java TCP/IP server and client socket application is created in this example. Java SE 8 and the Eclipse Neon IDE was used. It is also shown how to run the socket application with the java command and how to use Wireshark for monitoring TCP/IP network traffic between the server and client socket.

This chapter is from the book
Just Java 2, 5th Edition

This chapter is from the book

This chapter is from the book

A Server Socket in Java

This section shows a simple example of creating a server socket to listen for incoming requests. We could write the server side of a simple NTP server, but let's try something a little more ambitious. It should be fairly clear at this point that HTTP is just another of the many protocols that use sockets to run over the Internet.

A web browser is a client program that sends requests through a socket to the HTTP port on a server and displays the data that the server sends back. A basic web browser can be written in a couple of hundred lines of code if you have a GUI component that renders HTML, which Java does.

A web server is a server program that waits for incoming requests on the HTTP port and acts on those to send the contents of local files back to the requestor. It can be implemented in just a few dozen lines of code.

Security of Network Programs—A Cautionary Tale!

Be very careful when you start developing networked programs on your computer. Before you try it at work, check if there is a company policy about network use. You can get fired for doing the wrong thing!

The problem is that any server sockets you create may be visible more widely than you intended. If you are running this at home, and you are not using a firewall, your server socket will be visible to the entire net. That's like leaving the front door of your home wide open.

When I was developing the HTTP server in Java for this chapter, I left it running on my PC to test it. Someone's automated port scanner script soon noticed my server, made an unauthorized connection to it, and issued this HTTP command:

This is an attempt to break out of the scripts directory, run a shell, and do a 'dir' to see what's on my system. Crackers will try to add their own backdoor on your computer where you'll never find it. Then they can use your system whenever it's on the net (they love cable modems) for such things as distributed denial of service attacks. My server was logging client requests, but not fulfilling them, so the nimrod was out of luck. But be careful out there; people are actively looking for systems to break into.

The example here is part of the code for a web server. This is the code that opens a server socket on the http port, port 80, and listens for requests from web browsers. We echo the requests, but don't act on them.

The code is split into two classes to better show what's happening. The first class is the main program. It instantiates a server socket on port 80 (use port 1080 if you're on a Unix system without root access). The code then does an accept() on the server socket, waiting for client connections to come in. When one does come in, the program creates a new object to deal with that one connection and invokes its getRequest() method.

There are only two new lines of code in this server program. This line:

and this line:

The first line instantiates a server socket on the given port (httpd is an int with the value 80). The second line does an accept() on this server socket. It will block or wait here until some client somewhere on the net opens a connection to the same port, like this:

At that point, the accept() method is able to complete, and it returns a new instance of a socket to the server. The rest of this conversation will be conducted over the new socket, thus freeing up the original socket to do another accept() and wait for another client. At the client end, the socket doesn't appear to change.

In a real server, the code will loop around and accept another connection. We'll get to that. Here is the second half of the code: the OneConnection class that the main program uses to do the work for a single client request.

The constructor keeps a copy of the socket that leads back to the client and opens the input and output streams. Sockets always do I/O on bytes, not Unicode chars. HTTP is a line-oriented protocol. We push a BufferedReader onto the input stream so we can use the convenient readLine() method. DataInputStream has one of those too, but it is deprecated.

If you're using a binary protocol, do everything with streams, not readers/writers. We wrap a DataOutputStream on the output side of the socket. We don't write anything in this version of the program, but we will soon develop it and start writing.

Socket Protocols

The getRequest() method reads successive lines from the socket and echoes them on the server. How does it know when to stop reading lines? This is one of the tricky things with sockets—they cannot tell the difference between 'end of input' and 'there is more input, but it is delayed coming through the network.'

To cope with this inability to know when it's done, socket protocols use one of three approaches:

  • have the client precede each message by a number giving the length of the following message. Or use some other indication to end transmission, such as sending a blank line.

  • have the client close its output stream, using sock.shutDownOutput(). That causes the next read at the server end to return -1.

  • set a timeout on the socket, using sock.setSoTimeout(int ms). With this set to a non-zero amount, a read call on the input stream will block for only this amount of time. Then it will break out of it by throwing a java.net.SocketTimeoutException, but leaving the socket still valid for further use.

The third approach, using timeouts, is the least reliable because timeouts are always too long (wasting time) or too short (missing input). HTTP uses a mixture of approaches one and two.

Running the HTTP Server Program

Compile the code and then run the program. Make sure you run it on a computer that is not already running a web-server, otherwise it will find that it cannot claim port 80. If all is well, the program will print out:

then it will block, waiting for an incoming request on the port. This is exactly what a webserver does: opens port 80 and waits for incoming socket connections from clients.

Loopback Address

<Anchor1>Every computer system on the Internet has a unique IP address consisting of four groups of digits separated by periods like this: 204.156.141.229

They are currently revising and increasing the IP address specification so that there will be enough new IP addresses to give one to every conceivable embedded processor on earth, and a few nearby friendly planets. These version 6 addresses look like: 1080:0:0:0:8:800:200C:417A

One special version 4 IP address is: 127.0.0.1. This is the 'loopback' address used in testing and debugging. If a computer sends a packet to this address, it is routed to itself, without actually leaving the system. Thus, this special address can be used to run Internet software even if you are not connected to the Internet. Set your system up so that the Internet services it will be requesting are all at the loopback address. Make sure your system is actually running the demons corresponding to the services you want to use.

The hostname for the loopback address is 'localhost,' if you are requesting services by name rather than IP address. On any system, you should be able to enter the command 'ping localhost' and have it echo a reply from the loopback IP address. If you can't do this, it indicates that your TCP/IP stack is not set up properly.

Here's the interesting part. You can make that connection using any web browser! Just start up your browser and direct it to the computer where you are running the Java program. You can run your browser on a different system altogether, and give it the name of the computer running the Java program.Or, if you are running everything on one computer, the name will be 'localhost,' and the URL will be something like:

The rest of the URL doesn't matter since our server program doesn't (yet) do anything with the incoming request. You will see the Java server print out the message that a socket connection has been made ('got a socket'), and then print the HTTP text it receives on the socket from the browser!

These strings are HTTP headers. They are created by the browser to tell the server what file it has asked for, and they provide information about what kinds of format the browser can accept back.

A couple more points to note here. First, almost all servers uses threads. That way, they can serve the client and at the same time accept further requests. We will shortly show the code to do this. Second, these dozen or so lines of server code are at the heart of every webserver. If you add a couple of routines to read whatever file the browser asks for and write it into the socket, you have written a webserver. Let's do it.

The ServerSocket API is:

Write A Socket Program For Echo 2fping 2ftalk Commands In Javascript

The accept() method listens for a client trying to make a connection and accepts it. It creates a fresh socket for the server end of the connection, leaving the server socket free to do more accepts.

The bind() method is used to connect an existing socket to a particular IP address and port. You would use this when you want to use channels instead of streams for socket I/O; there's an example at the end of the chapter.

The other methods should be clear from their names. There are other methods in the API, but these are the main ones you will use.

Debugging Sockets

The little HTTPServer program we just saw can be used to help debug some server socket problems. You can see exactly what headers the browser sends you for different HTML requests. It works for other protocols too. If you make the code listen on another port, you can look at the incoming stream there.

Standing on the Corner, Watching All the Packets Go By

The server program, shown on the previous pages, will echo all the input that is sent to one socket. This is similar to the way that the FBI's controversial Carnivore program works.

Carnivore was created so that the FBI could do the online equivalent of phone tapping. It works at the more fundamental level of individual packets rather than sockets, but the principle is the same.

Carnivore is basically a packet sniffer that can be installed at an ISP and directed to copy packets that meet certain criteria (to or from a given IP address, for example). In this way, Carnivore can give the FBI a copy of all the email, all the web site visits, all the telnet sessions for a particular target over the course of a month or more. A court order is needed to authorize each use of Carnivore.

The FBI made a PR error by giving the program such an aggressive name. Law enforcement needs access to these tools to track down online fraud, network disruption, and other crimes. But they would have done themselves a favor by calling the software something calmer like 'Old Packet Collector.'

Another debugging technique uses the telnet program to look at incoming text to a client socket. Telnet's actual purpose is to open a command shell on a remote computer. The lines you type are sent over the socket connection, and the responses sent back the same way. However, you can tell telnet to use any port. The stream that it receives on that port will be displayed in the telnet window, and the things you type will be sent through the socket back to the server. The characters you type will be sent to the other end, but not echoed however.

Telnet is just a quick and dirty debugging technique to help you see what's going on. Figure 17–4 uses telnet to see what an NTP server is sending back. Most servers will close a socket as soon as they have given you the requested information, hence the 'connection lost' pop-up window. There is also a 'keep-alive' option to a socket that requests the connection be retained for expected use in the very near future. This is useful for HTTP.

Figure 17–4 Debugging with Telnet.

These days you should avoid the use of telnet and ftp for their main purpose, as they send passwords 'in the clear' to the remote socket. They are thus vulnerable to packet-sniffing by crackers at routers. Use SSH, the secure shell, instead. There is a Java implementation of SSH on the CD that comes with this book.

Using Netstat

Another useful tool for seeing what is going on with your network connection is netstat. It is available on Windows and Unix. Run netstat like this:

This shows all the current IP connections, the local socket, the remote socket, and the state. Netstat lets you see if you can at least make a connection to a remote system.

The '-?' option to netstat will give you a message about other options.

Finally, there's a very helpful website at straylight.cso.niu.edu. You can use one of their webpages (specifically, straylight.cso.niu.edu/cgi-bin/test-cgi.cmd) to see what is happening with your HTML pages. If you specify that web page as the 'Action' value for an HTML form, when you press the 'submit' button, the script will echo back to you everything that your form sent across. If this site goes off the net, try doing a websearch for 'CGI test forms'. Using an echo script makes it easy to see what is going on, and hence what you need to correct.

Echo%2fping%2ftalk

Getting the HTTP Command

Let's add a few lines of code (in bold) to our server to extract the HTTP 'GET' command that says what file the browser is looking for. We will develop this example by extending the OneConnection class. That way, we will add just the new code in the child class, and use the existing methods from the parent. The code in the new child class is:

The getRequest() method now looks at incoming HTTP headers to find the one containing a GET command. When it finds it, it writes an acknowledgement back to the browser (the '200 OK' line), and extracts the filename from the GET header. The filename is the return value of the method.

The main program will need to construct the OneConnection_A object and then call its getRequest() method. From here it is a small step to actually get that file and write it into the socket.

Never Use println() with Sockets!

The println() method is defined to output the platform specific line separator. This will be 'n' on Unix, 'r' on Macs, and 'rn' on Windows.

However, lots of TCP/IP protocols are line based, and the line is defined to end with carriage return line feed 'rn', or just line feed 'n'. So if you're on a Mac, the println method won't output something that a socket server recognizes as a complete end of line sequence.

The Mac client will do a println, which sends a 'r', and then wait for a response from the server. The server will get the 'r' and wait for a 'n' to complete the end of line sequence. Result: deadlock! Each end is waiting for something from the other. See Apple Tech Note 1157 for more on this:

developer.apple.com/technotes/tn/tn1157.html

The solution is to never use println with remote protocols on any platform. Always use explicit 'rn' characters when writing to a socket.

Here's a new class that is a child of OneConnection_A; it adds a method to get the file of the given name and write it into the socket. Since it knows how big the file is, it might as well generate the HTTP header that gives that information.

The main program will need to construct the OneConnection_B object and then add a call to its send file method. Now that our server has the ability to return files we need to build in some security. The first few lines of the method prepend the string '/tmp/' onto the filename. The code also checks that the filename does not contain the string '..' to enter a parent directory. These two limitations together ensure that the server will only return files from your tmp directory.

The 'Content-Length' and 'Content-Type' are two standard HTTP headers that help the browser deal with what you send it. The blank line tells the browser that is the end of the headers and the text that follows should be displayed.

At this point you should try compiling the code, placing a test html file in the tmp directory, and then starting the server. Browse the URL localhost/tmp/exam_ple.html and check that the browser displays the file correctly.

We have completed a basic webserver. That's quite an accomplishment! The next section looks at client side sockets again, in particular how to use a socket to pull information from a web page. It then shows the same task done by a URLConnection. We then describe the class that represents IP addresses and finish the chapter by making the web server multithreaded.

Related Resources

Write A Socket Program For Echo 2fping 2ftalk Commands In Java Runtime

  • eBook (Watermarked) $38.39
  • eBook (Watermarked) $38.39
  • Downloadable Video $996.00

Echo in Java is simple, isn’t it?But have you ever thought about how many ways there are to implement Echo in Java?I’ll show you some.And while I’m at it, I’ll also show you Echo in bash, C, Clojure, Common Lisp, Go, Groovy, JavaScript, Objective-C, Pascal, Perl, PHP, Prolog, Python, Ruby, Scala and Scheme.While this is mostly for developers who learn Java or another language, I hope that there will be one or two things that are also surprising for experienced developers in Java as well as other languages.

2ftalk

What is Echo? Requirements?

The echo command is a command found in almost all CLIs, like UNIX shells (sh, bash etc.), Windows cmd.exe etc. which will simply print all its arguments, concatenated with space, followed by newline.

Here are a few examples

So, arguments are concatenated with a single whitespace.The last argument will be printed without a following whitespace.In any case, the last thing printed will be a newline.

Java 8

Let’s look at Java 8 first, because it provides the most convenient solution.If you’re just interested in solving the problem nicely today, this is the preferred solution.

or, if you prefer without import static:

Iterative Java 1-4

Iterative Java 5-7

Recursive Java 1-4

Recursive Java 5-7 using List

Recursive Java 5-7 using ListIterator

Iterative Java 1-4 with less I/O overhead, w/o explicit StringBuffer

Iterative Java 1-4 with less I/O overhead, w/ explicit StringBuffer

Iterative Java 5-7 with less I/O overhead, w/o explicit StringBuilder

Iterative Java 5-7 with less I/O overhead, w/ explicit StringBuilder

Recursive Java 1-4 with less I/O overhead

Recursive Java 5-7 using List with less I/O overhead

Recursive Java 5-7 using ListIterator with less I/O overhead

bash

C

Iterative solution in C without counter

Iterative solution in C with counter

Recursive solution in C

Clojure

As we can see, the solution in Clojure is very simple.

Common Lisp

Go

Groovy

JavaScript

Objective-C

Basically the same as C, because no features of Objective-C are required.

Pascal

Perl

PHP

Write A Socket Program For Echo 2fping 2ftalk Commands In Java Compiler

Prolog

Behold the beauty of Prolog syntax!

Prolog has no support for joining strings.Still, the Prolog listing is very nice, it is beautiful.See how pattern matching, list operations and recursion make it very simple and straight forward.For an empty list, it outputs a newline.For a list with only one element, it outputs that element and recurses to the empty list.For any other list, it outputs the head element, a space, and recurses to the tail of the list.

Python

Ruby

Scala

Scheme

It’s obvious that there’s more than one way to solve a problem.Languages which provide a proper join() function via the API somehow make the life easier.Of all the languages that do not provide such a join() function and the writes are performed immediately, I like the solution in Prolog best.

Java 8 is awesome - almost!

What’s really nice about Java 8 is that the solution provided by Java 8 is the cleanest, shortest and fastest at the same time.That’s what functional programming really is about.

However, Java 8 didn’t manage to get rid of boilerplate.As many other programming languages - most notably, because being somewhat designed for the JVM, Clojure, Groovy and Scala - demonstrate, this boilerplate isn’t necessary at all.

Recursion in Java sucks

And that’s for more than just one reason.Recursion works best in languages with the following attributes:

Write A Socket Program For Echo 2fping 2ftalk Commands In Java Programming

  • Pattern matching method signatures
  • Tail recursion optimization
  • List slices
  • More than one return value (return list)

As we can see, Java supports neither of these.And that’s what makes writing recursive programs hard.

Before Java 8, Java provided too many ways how to solve the problem

Although Java 8 added yet one more way how to solve the problem, Java 8 made the situation much better.Before Java 8, a problem as simple as echo already turned into a trade-off between readability and performance.Clearly, for echo, performance wouldn’t be an issue anyway.I’m just saying, as there might be different, bigger problems.

TODO:2015-08-02:christian:3: Solutions in C++, C#, Assembly x86, Assembly x64, Assembly ARM, COBOL, Fortran, D, Scratch, Lua, F#, Erlang, Haskell, Awk, bash, Eiffel, Modula-2, OCaml, Oberon, ML, SmallTalk, TcL, R, Dart, Ada, Logo, Whitespace, Brainfuck, Befunge, LOLCODE, Malbolge, Cluster, Kotlin