Take a look at the socket information in the networking tutorial:
http://java.sun.com/docs/b
Main Topics
Browse All TopicsHi,
I need to write a simple application in Java, that listens for incoming data on a particular port and does something with it. I know the data will be sent from a GPRS device, so the device will establish a connection and then send the data to the address and port my app will listen on. I don't need to worry about the GPRS connection stuff. Just the data sent over the connection once it is established. I assume the data will be wrapped up in packets of some sort so that it can be sent over the GPRS connection?
I don't know whether I need to do some sort of handshake with the GPRS device in order to accept its packets? Is there a free java app out there that can do this sort of thing? It is effectively IP traffic so I should imagine it is easily handled within Java's APIs?
Any code snippets to get me started would be really welcome!
Thanks
Scott
This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.
Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.
If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.
Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.
Access the answers to your technology questions today.
30-day free trial. Register in 60 seconds.
Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Try it out and discover for yourself.
30-day free trial. Register in 60 seconds.
Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.
Take a look at the socket information in the networking tutorial:
http://java.sun.com/docs/b
You need to know the 'port' on which the GPRS device will connect. That will be a number, possibly greater than 1000. Once you know that, the basic steps you would follow are like this:
1. Set up a ServerSocket object which listens at that port. Let's say the GPRS will connect to port 7000:
(import java.net.*;)
(import java.io.*;)
ServerSocket srvGPRS = new ServerSocket( 7000);
2. Accept connections. Depending on your application, you might accept more than one connection at a time.
Socket sckGPRS = srvGPRS.accept();
3. The Socket object represents a connection to a single device. Now get the Input Stream and Output Stream so you can talk. If your server can talk to several devices at once, you may want to do this in its own thread. But to answer your question, I will just go forward with a single conversation.
InputStream isGPRS = sckGPRS.getInputStream();
OutputStream osGPRS = sckGPRS.getOutputStream( );
4. If the GPRS speaks in bytes, you can read and write bytes directly to the input and output stream. However, if the protocol is text, you might find it more convenient to build a BufferedReader (to read strings from the device) and a PrintWriter (to send strings back to the device).
BufferedReader brGPRS = new BufferedReader( new InputStreamReader( isGPRS));
PrintWriter pwGPRS = new PrintWriter( osGPRS));
5. Assuming the protocol is based on Strings, you can now read from the device and write to the device like this:
String sGPRSStatus = brGPRS.readLine();
... process the information. Maybe read more lines
pwGPRS.println( "OK");
6. When the conversation is complete, you should close the streams and the socket:
brGPRS.close();
pwGPRS.close();
sckGPRS.close();
7. At this point, you can listen for a new device by going back to step 2 -- caling ServerSocket.accept(). Or close the server socket and finish
srvGPRS.close();
May be this example can help you:
package by.cis;
import java.io.*;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.*;
import java.net.Socket;
import java.net.UnknownHostExcept
/**
* This is a test application which obtains clients information using
* Western Bridge to Briz corba server application protocol.
*
*@author S. Berdachuk (Berdachuk@tut.by)
*@created Nov 2003 ã.
*@version 0.1
*/
public class TstClient {
/**
* This constructor manages the retrieval of the client information.
*
*@param args Description of the Parameter
*/
public TstClient(String[] args) {
if (contactServer()) {
receiveResponse(args[0]);
}
quitServer();
}
// Timestamp of data.
/**
* Start the application running, first checking the arguments, then
* instantiating a StockQuoteClient, and finally telling the instance to
* print out its data.
*
*@param args Arguments which should be <server> <stock ids>
*/
public static void main(String[] args) {
TstClient client = new TstClient(args);
client.printResultInfo(Sys
System.exit(0);
}
/**
* Open the initial connection to the server.
*
*@return The initial connection response.
*/
protected boolean contactServer() {
try {
// Open a socket to the server.
socket = new Socket(SERVER_NAME, SERVER_PORT);
// Obtain I/O streams.
dataReader = new DataInputStream(new BufferedInputStream(socket
dataOutput = new DataOutputStream(new BufferedOutputStream(socke
} catch (UnknownHostException excpt) {
System.err.println("Unknow
": " + excpt);
} catch (IOException excpt) {
System.err.println("Failed
": " + excpt);
}
return ((socket != null) && (dataReader != null) && (dataOutput != null));
}
/**
* This method asks for all of the stock info.
*
*@param inputInfo Description of the Parameter
*/
protected void receiveResponse(String inputInfo) {
String response;
// If the connection is still up.
if (connectOK()) {
//try {
// Send query to server, calk packet length
int len = inputInfo.length() + 2;
int b1 = (int) len / 256;
int b2 = (int) (len - len / 256);
try {
dataOutput.writeByte(b1);
dataOutput.writeByte(b2);
dataOutput.writeBytes(inpu
dataOutput.flush();
//Read packet length
b1 = dataReader.readByte();
b2 = dataReader.readByte();
int length = b1 * 256 + b2;
byte[] dataPacket = new byte[length];
//Read packet
int count = dataReader.read(dataPacket
if (count < 0) {
throw new IOException();
}
} catch (IOException e) {
}
}
}
/**
* This method disconnects from the server.
*
*/
protected void quitServer() {
try {
// If the connection is up, send a QUIT message
if (connectOK()) {
this.receiveResponse("0");
}
// Close the streams and the socket if the
// references are not null.
if (dataOutput != null) {
dataOutput.close();
}
if (dataReader != null) {
dataReader.close();
}
if (socket != null) {
socket.close();
}
} catch (IOException ex) {
System.err.println("Failed
SERVER_NAME + ": " + ex);
}
}
/**
* This method prints out a report on the various requested stocks.
*
*@param sendOutput Where to send output.
*/
public void printResultInfo(PrintStrea
// Provided that we actually received a HELLO message:
if (returnedInfo != null) {
sendOutput.print("INFORMAT
+ "\n\tCurrent As Of: " + returnedInfo + "\n\n");
}
}
/**
* Conveniently determine if the socket and streams are not null.
*
*@return true if the connection is OK.
*/
protected boolean connectOK() {
return (dataOutput != null && dataReader != null && socket != null);
}
final static int BUFFER_SIZE = 0x1000;
final byte[] byteArray = new byte[BUFFER_SIZE];
private Socket socket = null;
private DataInputStream dataReader = null;
private DataOutputStream dataOutput = null;
private String returnedInfo = null;
private final static int SERVER_PORT = 1717;
private final static String SERVER_NAME = "10.0.0.215";
}// TstClient
//////////////////////////
package by.cis;
import by.cis.ClientHandler;
import by.cis.ServerConstants;
import java.io.*;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
/**
*@author S. Berdachuk (Berdachuk@tut.by)
*@created Nov 2003.
*@version 0.1
*/
public final class Server {
/**
* The constructor creates an instance of this class, loads the stock data,
* and then our server listens for incoming clients.
*
*@param args Description of the Parameter
*/
public Server(String[] args) {
init();
//CheckParams(args);
for (int i = 0; i < args.length; i++) {
String s = args[i];
char c1 = s.charAt(0);
if (c1 != '-' && c1 != '/') {
break;
}
if (s.length() > 1) {
String s1 = s.substring(1);
if (s1.startsWith("port=")) {
if (s1.length() > 5) {
String s2 = s1.substring(5);
serverProperties.setProper
} else {
break;
}
}
} else {
break;
}
}
try {
// Create a listening socket.
socket = new ServerSocket(
serverProperties.getIntege
, serverProperties.getIntege
);
print("Started. Listen port: "
+ serverProperties.getIntege
);
} catch (IOException excpt) {
errWriter.println("Unable to listen on port " +
serverProperties.getIntege
System.exit(1);
}
}
/**
* Retrieves a String identifying this Server object.
*
*@return a String identifying this Server
*/
public String getServerId() {
return serverId;
}
/**
* Initializes this server, setting the accepted connection protocol. This
* method is only called from the constructor
*/
private void init() {
serverId = toString();
serverId = serverId.substring(serverI
serverState = ServerConstants.SERVER_STA
serverProperties = getDefaultServerProperties
logWriter = new PrintWriter(System.out);
errWriter = new PrintWriter(System.err);
}
/**
* Description of the Method
*
*@param as Description of the Parameter
*@return Description of the Return Value
*/
protected static boolean CheckParams(String as[]) {
try {
for (int i = 0; i < as.length; i++) {
String s = as[i];
char c1 = s.charAt(0);
if (c1 != '-' && c1 != '/') {
return false;
}
if (s.length() > 1) {
String s1 = s.substring(1);
if (s1.startsWith("port=")) {
if (s1.length() > 5) {
String s2 = s1.substring(5);
//serverProperties.setProp
} else {
return false;
}
}
} else {
return false;
}
}
} catch (Exception exception) {
return false;
}
return true;
}
/**
* Prints the specified message, s, formatted to identify that the print
* operation is against this server instance.
*
*@param msg The message to print
*/
final synchronized void print(String msg) {
PrintWriter writer = logWriter;
if (writer != null) {
writer.println("[" + serverId + "]: " + msg);
writer.flush();
}
}
final void trace(String msg) {
print("[" + Thread.currentThread() + "]: " + msg);
}
/**
* Sets the server state value.
*
*@param state the new value
*/
protected final synchronized void setState(int state) {
serverState = state;
}
/**
* Prints an error message to this Server object's errWriter. The message
* is formatted similarly to print(String), additionally identifying the
* current (calling) thread.
*
*@param msg the message to print
*/
final synchronized void printError(String msg) {
PrintWriter writer = errWriter;
if (writer != null) {
writer.print("[" + serverId + "]: ");
writer.print("[" + Thread.currentThread() + "]: ");
writer.println(msg);
writer.flush();
}
}
/**
* Description of the Method
*
*@exception Throwable Description of the Exception
*/
protected void finalize() throws Throwable {
//if (serverThread != null) {
releaseServerSocket();
//}
}
/**
* Description of the Method
*/
private final void releaseServerSocket() {
trace("releaseServerSocket
if (socket != null) {
trace("Releasing server socket: [" + socket + "]");
setState(ServerConstants.S
try {
socket.close();
} catch (IOException e) {
printError("Exception closing server socket");
printError("releaseServerS
}
socket = null;
}
trace("releaseServerSocket
}
/**
* Gets the defaultServerProperties attribute of the Server object
*
*@return The defaultServerProperties value
*/
private static final ServerProperties getDefaultServerProperties
ServerProperties serverProperties;
serverProperties = new ServerProperties();
serverProperties.setProper
serverProperties.setProper
return serverProperties;
}
/**
* Starts up the application.
*
*@param args Ignored command line arguments.
*/
public static void main(String[] args) {
Server server = new Server(args);
server.serveClients();
}
/**
* This method waits to accept incoming client connections.
*/
public void serveClients() {
Socket clientSocket = null;
try {
while (keepRunning) {
// Accept a new client.
clientSocket = socket.accept();
print("socket accepted");
// Create a new client handler.
ClientHandler newHandler = new ClientHandler(clientSocket
Thread newHandlerThread = new Thread(newHandler);
newHandlerThread.start();
}
socket.close();
} catch (IOException excpt) {
System.err.println("Failed
}
}
/**
* This method allows the server to be stopped.
*/
protected void stop() {
if (keepRunning) {
keepRunning = false;
}
}
// A boolean used to keep the server looping until/ interrupted.
private boolean keepRunning = true;
private volatile int serverState;
private ServerProperties serverProperties;
private ServerSocket socket = null;
private PrintWriter logWriter;
private PrintWriter errWriter;
/**
* Description of the Field
*/
protected String serverId;
private static int mode;
}// Server
//////////////////////////
package by.cis;
import java.io.BufferedInputStrea
import java.io.BufferedOutputStre
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
/**
* This class use used to manage a connection to a specific client.
*
*@author S. Berdachuk
*@created Nov 2003.
*/
class ClientHandler implements Runnable {
/**
* The constructor sets up the necessary instance variables.
*
*@param newSocket Socket to the incoming client.
*/
public ClientHandler(Socket newSocket) {
clientSocket = newSocket;
clientInetAddress = newSocket.getInetAddress()
println("client connected");
}
/**
* This is the thread of execution which implements the communication.
*/
public void run() {
//String inputLine;
String operationId;
try {
dataOutput =
new DataOutputStream(new BufferedOutputStream(clien
dataReader =
new DataInputStream(new BufferedInputStream(client
//Read client messages and respond
while (true) {
//Read packet length
int b1 = dataReader.readByte();
int b2 = dataReader.readByte();
int length = b1 * 256 + b2 - 2;
byte[] dataPacket = new byte[length];
//Read packet
int count = dataReader.read(dataPacket
if (count < 0) {
throw new IOException();
}
//Quit
if (dataPacket[0] == 48) {
break;
}
//Try make payment
else if (dataPacket[0] == 49) {
String inputLine = new String(dataPacket, 0, count);
StringBuffer inf = new StringBuffer();
PaymentInfo paymentInfo = new PaymentInfo(inputLine);
println("received: " + inputLine);
int reslt = paymentInfo.getInfo(inf);
sendRespond((byte) reslt, inf.toString());
inf = null;
}
// Unknown command.
else {
dataOutput.flush();
sendRespond((byte) 3, "ERROR. UNKNOWN COMMAND");
}
}
} catch (IOException excpt) {
println(" Failed I/O: " + excpt);
// Finally close the streams and socket.
} finally {
try {
if (dataOutput != null) {
dataOutput.close();
}
if (dataReader != null) {
dataReader.close();
}
if (clientSocket != null) {
clientSocket.close();
}
println("client disconnected");
} catch (IOException excpt) {
println(" Failed I/O: " + excpt);
}
}
}
/**
* Description of the Method
*
*@param cmd Description of the Parameter
*@param info Description of the Parameter
*@exception IOException Description of the Exception
*/
private void sendRespond(byte cmd, String info) throws IOException {
byte[] bArray = info.getBytes();
int len = bArray.length + 3;
byte b1 = (byte) (len / 256);
byte b2 = (byte) (len - len / 256);
dataOutput.writeByte(b1);
dataOutput.writeByte(b2);
dataOutput.writeByte(cmd);
dataOutput.write(bArray);
dataOutput.flush();
println("Packet length: " + len);
println("sended: " + b1 + " " + b2 + " " + cmd + " " + info);
}
/**
* Description of the Method
*
*@param msg Description of the Parameter
*/
/*
* public void internalWait(int ms) {
* long t1 = new GregorianCalendar().getTim
* while ((new GregorianCalendar().getTim
* }
* }
*/
/**
* Description of the Method
*
*@param msg Description of the Parameter
*/
final synchronized void println(String msg) {
System.out.println(clientI
}
private String clientInetAddress;
private Socket clientSocket = null;
private DataOutputStream dataOutput = null;
private DataInputStream dataReader = null;
} // ClientHandler
Business Accounts
Answer for Membership
by: markbrdslyPosted on 2003-12-16 at 08:42:18ID: 9950390
Hello Scott
I have to admit that I have never done anything like this but I would reccommend that you take a look at the dcoumentation for the ServerSocket class.
To quote what Sun say, "This class implements server sockets. A server socket waits for requests to come in over the network. It performs some operation based on that request, and then possibly returns a result to the requester."
I have taken a quick look myself and think - I emphasise think at this stage - that you will create an instance of the ServerSocket class and bind it to a specific port and there is a construtor provided to do just this. That instances accept method will then listen for a connection and will return an instance of the Socket class once that connection has been made. Once you have a socket, it is possible to open an InputStream on that object and possibly read the data that way.
For now, that is all the help I can offer.
Yours
Mark B