how to send and receive data between client and server with JPOS? - java

i have an ISO8583 message to send between a client and a server (through sockets). What i did is declare socket and serverSockets classes, start server and accept connections, then create channel both on server and client to apply receive and send methods.
What i got is i cannot print the iso8583 message i send. here is the complete code :
The server's side code :
public class SocketServer {
private ServerSocket serverSocket;
private Socket clientSocket;
private PrintWriter out;
private BufferedReader in;
public void start(int port) throws IOException, ISOException {
serverSocket = new ServerSocket(port);
clientSocket = serverSocket.accept();
ISOChannel channel = new ASCIIChannel (
"localhost", 5000, new ISO87APackager() );
channel.connect();
ISOMsg r = channel.receive ();
System.out.println("isoMsg result "+r.getMTI());
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String data = in.readLine();
System.out.println("Inside Server Socket: " + data);
out.println("Data from server: " + data);
}
public void stop() throws IOException {
in.close();
out.close();
clientSocket.close();
serverSocket.close();
}
public static void main(String[] args) throws IOException, ISOException {
SocketServer server = new SocketServer();
server.start(5000);
System.out.println("Server start...");
}
}
and the client's code :
public class Client
{
public Client(String address, int port) throws ISOException
{
// establish a connection
try
{
Socket socket = new Socket(address, port);
System.out.println("Connected");
ISOChannel channel = new ASCIIChannel (
"localhost", 5000, new ISO87APackager() );
channel.connect();
ISOMsg r=new ISOMsg();
r.setMTI("0200");
channel.send(r);
InputStream in2= socket.getInputStream();
OutputStream out2=socket.getOutputStream();
String line = "";
try
{
in2.close();
out2.close();
socket.close();
}
catch(IOException i)
{
i.printStackTrace();
}
}catch(IOException e){
e.printStackTrace();
}
}
public static void main(String args[]) throws ISOException
{
Client client = new Client("localhost", 5000);
}
}

Related

ObjectoutStram not set when trying to connect two client Socket to a server

I Have Class like below trying to connect two client socket to a server but when they get accepted by server I can only send data to the server through first socket (named s1 in code) and the second socket can do not send data to the server
public class Client_1 {
public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
Socket s1 = new Socket("localhost", 8888);
Socket s2 = new Socket("localhost", 8888);
BufferedOutputStream bos1 = new BufferedOutputStream(s1.getOutputStream());
ObjectOutputStream oos1 = new ObjectOutputStream(bos1);
oos1.flush();
BufferedOutputStream bos2 = new BufferedOutputStream(s2.getOutputStream());
ObjectOutputStream oos2 = new ObjectOutputStream(bos2);
oos2.flush();
BufferedInputStream bis1 = new BufferedInputStream(s1.getInputStream());
ObjectInputStream ois1 = new ObjectInputStream(bis1);
BufferedInputStream bis2 = new BufferedInputStream(s2.getInputStream());
ObjectInputStream ois2 = new ObjectInputStream(bis2);
oos1.writeObject("a message from first client s1");
oos1.flush();
oos2.writeObject("a message from second client s2"); // sever does not receive this one
oos2.flush();
}
}
here is server code waiting for client
public class Main {
public static void main(String[] args) throws IOException {
WaitForClient();
}
public static void WaitForClient() throws IOException {
ServerSocket serverSocket = new ServerSocket(8888);
int i = 0;
while(true) {
Socket client = serverSocket.accept();
i++;
System.out.println(i + " client connected");
ClientThread clientThread = new ClientThread(client);
Thread thread = new Thread(clientThread);
thread.setDaemon(true);
thread.start();
}
}
and this is ClientThread who get info from socket
public class ClientThread implements Runnable {
Socket clientSocket;
ObjectInputStream oIStream;
ObjectOutputStream oOStream;
Object inputObject;
BufferedInputStream bIS;
BufferedOutputStream bOS;
public ClientThread(Socket clientSocket) {
this.clientSocket = clientSocket;
}
#Override
public void run() {
try {
bOS = new BufferedOutputStream(clientSocket.getOutputStream());
bIS = new BufferedInputStream(clientSocket.getInputStream());
oOStream = new ObjectOutputStream(bOS);
oOStream.flush();
oIStream = new ObjectInputStream(bIS);
while (clientSocket.isConnected()) {
if (bIS.available() > 0) {
inputObject = oIStream.readObject();
doService(inputObject);
System.out.println(inputObject.toString());
inputObject = null;
}
}
System.out.println("connection is closed!!!");
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
System.out.println("socket exception" + e.getMessage());
}
}
}
and this is what printed to console
1 client connected
2 client connected
a message from first client s1 // input from the first socket but nothing from the second socket
This code should work,Are you getting any error in doService method?. In case any exception while loop will break and print statement will not be executed. Otherwise it should print data from both client

How to fix "no communication between server and client"

This is code provided to me for a class. I am trying trying to fix a connection problem between the client and server. Even when both are started they do not connect.
This is for a Java based game of Battleship that will allow two users on separate devices to play one another. I'm not sure why the two do not connect and even the debugger has not been much help in directing me to the problem.
public class GameClient
{
private Socket clientSocket;
private PrintWriter out;
private BufferedReader in;
public void openConnection(String ip, int port)
{
try
{
clientSocket = new Socket(ip, port);
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
}
catch (Exception e)
{
System.out.println("Error opening client socket");
}
}
public String sendMessage(String msg)
{
String resp = "";
try
{
out.println(msg);
resp = in.readLine();
}
catch (Exception e)
{
System.out.println("Error sending message from Client");
}
return resp;
}
public void stop()
{
try
{
in.close();
out.close();
clientSocket.close();
}
catch (Exception e)
{
System.out.println("Error stopping client");
}
}
public static void main(String[] args)
{
GameClient client = new GameClient();
client.openConnection("10.7.232.200", 3333);
String response = client.sendMessage("1,2");
System.out.println(response);
client.stop();
}
}
public class GameServer
{
private ServerSocket serverSocket;
private Socket clientSocket;
private PrintWriter out;
private BufferedReader in;
public void start(int port)
{
try
{
serverSocket = new ServerSocket(port);
clientSocket = serverSocket.accept();
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String move = in.readLine();
System.out.println(move);
out.println("6,1");
}
catch (Exception e)
{
System.out.println("Socket opening error");
}
}
public void stop()
{
try
{
in.close();
out.close();
clientSocket.close();
serverSocket.close();
}
catch (Exception e)
{
System.out.println("Error closing sockets");
}
}
public static void main(String [] args)
{
GameServer server = new GameServer();
server.start(3333);
server.stop();
}
}
public class PlayBattleship
{
public static void main(String[] args)
{
GameClient client = new GameClient();
client.openConnection("10.7.232.200", 3333);
//System.out.println(response);
BattleshipGame game = new BattleshipGame();
while (!game.checkEndgame())
{
game.getGuess(client);
}
client.stop();
}
}
The client and server should connect and stay connected till the game has reached completion
EDIT: I have thoroughly read the API documentation but still cannot understand the problem.
The Server in your code isn't waiting for the incoming requests, it only serves a single incoming request and then kills itself due to the nature of the main method which starts it.
You need to have the server wait for the requests and do not die. Check the code snippet below to understand the logic.
Plus, always try to throw the exceptions if you can't do anything meaningful with it within the method it is caught in. In your code the main method of the server will anyway execute even if there is an exception caught in the start method
public class GameServer {
private ServerSocket serverSocket;
private Socket clientSocket;
private PrintWriter out;
private BufferedReader in;
public ServerSocket start(int port) throws IOException {
serverSocket = new ServerSocket(port);
return serverSocket;
}
public void stop() throws IOException {
in.close();
out.close();
clientSocket.close();
serverSocket.close();
}
// This method accepts and serves the incoming requests
public void acceptConnection(ServerSocket serverSocket) throws IOException {
clientSocket = serverSocket.accept();
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String move = in.readLine();
System.out.println(move);
out.println("6,1");
}
public static void main(String[] args) throws IOException {
GameServer server = new GameServer();
ServerSocket serverSocket = server.start(3333);
System.out.println("Server Started");
// The effective change you need to make
// Loop through the incoming requests
while(true) {
server.acceptConnection(serverSocket);
}
}
}
public class GameClient {
private Socket clientSocket;
private PrintWriter out;
private BufferedReader in;
public void openConnection(String ip, int port) throws IOException {
clientSocket = new Socket(ip, port);
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
}
public String sendMessage(String msg) throws IOException {
String resp = "";
out.println(msg);
resp = in.readLine();
return resp;
}
public void stop() throws IOException {
in.close();
out.close();
clientSocket.close();
}
public static void main(String[] args) throws IOException {
GameClient client = new GameClient();
client.openConnection("10.7.232.200", 3333);
String response = client.sendMessage("1,2");
System.out.println(response);
client.stop();
}
}

Client-to-Client with server intermediary

I am trying to implement Client to Client which passes through the server. Client1 sends a line to the server and server forwards it to all the other clients.
Can you point out my mistake. Nothing is printed on the other clients.
Server Code:
public class Server {
int port;
ServerSocket server=null;
Socket socket=null;
ExecutorService exec = null;
ArrayList clients = new ArrayList();
DataOutputStream dos=null;
public static void main(String[] args) throws IOException {
Server serverobj=new Server(2000);
serverobj.startServer();
}
Server(int port){
this.port=port;
exec = Executors.newFixedThreadPool(3);
}
public void startServer() throws IOException {
server=new ServerSocket(2000);
System.out.println("Server running");
while(true){
socket=server.accept();
dos = new DataOutputStream(socket.getOutputStream());
clients.add(dos);
ServerThread runnable= new ServerThread(socket,new ArrayList<>(clients),this);
exec.execute(runnable);
}
}
private static class ServerThread implements Runnable {
Server server=null;
Socket socket=null;
BufferedReader brin;
Iterator it=null;
Scanner sc=new Scanner(System.in);
String str;
ServerThread(Socket socket, ArrayList clients ,Server server ) throws IOException {
this.socket=socket;
this.server=server;
System.out.println("Connection successful with "+socket);
brin=new BufferedReader(new InputStreamReader(socket.getInputStream()));
it = clients.iterator();
}
#Override
public void run() {
try{
while ((str = brin.readLine()) != null) {
while (it.hasNext()) {
try{
DataOutputStream dost=(DataOutputStream) it.next();
dost.writeChars(str);
dost.flush();
}
catch(IOException ex){
System.out.println("Error 1 "+ex);
}
}
}
brin.close();
socket.close();
}
catch(IOException ex){
System.out.println("Error 2 "+ex);
}
}
}
}
Client 1 code:
public class Client1 {
public static void main(String args[]) throws IOException{
String str;
Socket socket=new Socket("127.0.0.1",2000);
PrintStream prout=new PrintStream(socket.getOutputStream());
BufferedReader bread=new BufferedReader(new InputStreamReader(System.in));
BufferedReader dis=new BufferedReader(new InputStreamReader(socket.getInputStream()));
while(true){
System.out.println("Send to others:");
str=bread.readLine();
prout.println(str);
}
}
}
Other Clients:
public class Client2 {
public static void main(String args[]) throws IOException{
String str;
Socket socket=new Socket("127.0.0.1",2000);
BufferedReader dis=new BufferedReader(new InputStreamReader(socket.getInputStream()));
while(true){
str=dis.readLine();
System.out.print("Message: "+str+"\n");
}
}
}
Please help.. I have been at it for 2 days...

Pushing changes from one client to all other connected clients through server?

So I have a client:
public class TalkClient extends Thread
{
private int port;
private String host;
DocCntl theDocCntl;
public TalkClient(String host, int port) throws IOException
{
this.host = host;
this.port = port;
theDocCntl = new DocCntl(this);
}
public void run()
{
try
{
System.out.println("Seeking connection...");
Socket socket = new Socket(host, port);
DataInputStream in = new DataInputStream(socket.getInputStream());
BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
}catch(IOException e)
{
e.printStackTrace();
}
}
public static void main(String [] args)
{
int port = 5050;
try
{
Thread t = new TalkClient("127.0.0.1", port);
t.start();
}catch(IOException e)
{
e.printStackTrace();
}
}
public void pushToServer(){
String theData = this.theDocCntl.theDoc.docTA.getText();
}
}
And I have a server:
public class TalkServer extends Thread
{
private ServerSocket serverSocket;
public static DocCntl theCntl;
public TalkServer(int port) throws IOException
{
serverSocket = new ServerSocket(port);
}
public void run()
{
try
{
System.out.println("Listening for connections...");
Socket client = serverSocket.accept();
DataInputStream in = new DataInputStream(client.getInputStream());
BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
DataOutputStream out = new DataOutputStream(client.getOutputStream());
}catch(IOException e)
{
e.printStackTrace();
}
}
public static void main(String [] args)
{
int port = 5050;
try
{
Thread t = new TalkServer(port);
t.start();
}catch(IOException e)
{
e.printStackTrace();
}
}
}
In the client, I have a method called pushToServer, which I want to take the String data from a textArea on the client, and then push that to all the other connected clients. But I'm not sure how to handle sending the message to each individual connected client through the sockets. I've given it some thought, and I think I need to do 3 things:
1) Create and maintain a list of connected clients(threads). In the server class itself? Or in another class?
2) On the server, have some means of 'catching' the String data from one client, and then pushing it to all the other clients. This is why(I think) I need the list of clients. If I can figure out how to catch this(maybe through the input stream?) and then iterate through the list of clients to their text areas.
3) On the client side, I need to be able to catch the string from the server.
Any help on these 3 things would be greatly appreciated.

Java Client-Server application pipe not working on child thread

I have a client and a server. The client binds a socket on a specific port, the server sends back a new port to the client and the client should bind a new socket on the new port number.
From the main server thread, I start a thread that sends a message to the client once the server is ready and is listening to the new port, so that the client can attempt to connect to the new port. The pipe from the child thread is not sending the message to the client.
So both client and server just freeze, it seems like a deadlock, but im not sure. This line of code in the client: System.out.println("FROM SERVER: " + inMsg_rport); is not executing.
Server Code:
class server
{
public static void main(String argv[]) throws Exception
{
String newPort;
ServerSocket serverSocket = null;
Socket clientSocket = null;
try
{
serverSocket = new ServerSocket(5555);
clientSocket = serverSocket.accept();
DataOutputStream serverOut =
new DataOutputStream(clientSocket.getOutputStream());
int r_port = 5556;
Thread appThread = new Thread(new serverApp(serverOut, r_port));
appThread.start();
}
catch(IOException e)
{
System.out.println(e);
}
}
static class serverApp implements Runnable
{
DataOutputStream serverOut;
int nPort;
public serverApp(DataOutputStream servO, int r_port)
{
this.serverOut = servO;
this.nPort = r_port;
}
#Override
public void run()
{
ServerSocket serverSocket = null;
Socket clientSocket = null;
try
{
serverSocket = new ServerSocket(nPort);
serverOut.writeBytes(sr_port);
clientSocket = serverSocket.accept();
}
catch(IOException e)
{
System.out.println(e);
}
}
}
}
Client code:
class client {
public static void main(String argv[]) throws Exception
{
String serverIp = argv[0];
String msg = argv[2];
int port = Integer.parseInt(argv[1]);
Socket clientSocket = new Socket(InetAddress.getByName(serverIp), port);
BufferedReader clientIn =
new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));
String inMsg_rport = clientIn.readLine();
System.out.println("FROM SERVER: " + inMsg_rport);
int r_port = Integer.parseInt(inMsg_rport);
clientSocket.close();
System.out.println("Closed connection");
Socket new_clientSocket = new Socket(InetAddress.getByName(serverIp), r_port);
}
}
readLine() in your client is a blocking call, waiting for an end-of-line character
http://docs.oracle.com/javase/6/docs/api/java/io/BufferedReader.html#readLine()
You aren't sending an end of line character. You're using a DataOutputStream in your server and sending raw bytes.
Don't use a DataOutputStream in your server; I don't think that's really what you're looking for. Just send the port number as text with an end of line character and be done with it.

Categories

Resources