Java server / client sending array, Check in check out - java

Im having a little problem i have managed to send info from client to server etc... but i want to be able to do it though telnet also (Open it up and say go telnet 127.0.0.1 4444, and then put in like 1 2 3 and then it comes up in the server just like it would if sending via the client. At the moment im getting this error:
java.io.StreamCorruptedException: invalid stream header: 310D0A32
at java.io.ObjectInputStream.readStreamHeader(Unknown Source)
at java.io.ObjectInputStream.<init>(Unknown Source)
at ConnectionHandler.run(server1.java:73)
at java.lang.Thread.run(Unknown Source)
Let me know if i'm doing anything wrong please:
My main goal for this is to have it so i can enter say Username, ID and Name and then be able to recall them with a time, Like a very simple check in check out system. Would really love some help <3 :)
Client:
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class client1 {
public static void main(String[] args) {
try {
// Create a connection to the server socket on the server application
Socket socket = new Socket("localhost", 7777);
// Send a message to the client application
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
//oos.writeObject("A B C");
String data[]=new String[3];
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter details for the array");
for(int x=0;x<3;x++){
System.out.print("Enter word number"+(x+1)+":");
data[x]=br.readLine();
}
oos.writeObject(data);
System.out.println("Details sent to server...");
oos.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Server:
import java.io.IOException;
import java.io.ObjectInputStream;
import java.lang.ClassNotFoundException;
import java.lang.Runnable;
import java.lang.Thread;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class server1
{
private ServerSocket server;
private int port = 4444;
public server1()
{
try
{
server = new ServerSocket(port);
}
catch (IOException e)
{
e.printStackTrace();
}
}
public static void main(String[] args)
{
server1 example = new server1();
example.handleConnection();
}
public void handleConnection()
{
System.out.println("Waiting for client message got...");
// The server do a loop here to accept all connection initiated by the
// client application.
while (true)
{
try
{
Socket socket = server.accept();
new ConnectionHandler(socket);
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
class ConnectionHandler implements Runnable
{
private Socket socket;
public ConnectionHandler(Socket socket)
{
this.socket = socket;
Thread t = new Thread(this);
t.start();
}
public void run()
{
try
{
// Read a message sent by client application
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
String message[] = (String[]) ois.readObject();
//System.out.println("Message Received from client: " + message);
//b(message);
printArray(message);
ois.close();
socket.close();
System.out.println("Waiting for client message is...");
}
catch (IOException e)
{
e.printStackTrace();
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
}
private void b(String message) {
List<String> list = new ArrayList<String>();
String[] arr = list.toArray(new String[0]);
System.out.println("Array is " + Arrays.toString(arr));
}
private void printArray(String[] arr){
for(String s:arr){
System.out.println(s);
}
}

Related

socket programming transfer data from server to server

i have a client_1 , centerlized_server and server_1
the client send request to a centerlized_server
and centerlized_server transfer the request to the server_1
the problem is how i transfer the request from centerlized_serve to server_1??
I appreciate your help
...
Client1 code
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class Client1 {
private Socket server;
private ObjectOutputStream out;
private ObjectInputStream in;
public Client1() {
try
{
server = new Socket("localhost", 5050);
out = new ObjectOutputStream(server.getOutputStream());
in = new ObjectInputStream(server.getInputStream());
while (true)
{
Scanner s = new Scanner(System.in);
System.out.println("press 2 to date or 1 for time:");
Message msg = new Message();
msg.Type = s.nextInt();
out.writeObject(msg);
msg = (Message) in.readObject();
System.out.println(msg.message);
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
public static void main(String[] args) {
new Client1();
}
}
CernterlizedServer code
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.Date;
public class CentralizedServer extends Thread {
private Socket client;
private ObjectOutputStream out;
private ObjectInputStream in;
public CentralizedServer(Socket current_socket)
{
try
{
client = current_socket;
out = new ObjectOutputStream(client.getOutputStream());
in = new ObjectInputStream(client.getInputStream());
}
catch (Exception ex) {
ex.printStackTrace();
}
}
#Override
public void run()
{
try
{
while (true)
{
Message msg = (Message) in.readObject();
if (msg.Type == 1)
{
OnTimeRequst();
}
else if (msg.Type == 2)
{
OnDateRequst();
}
}
}
catch (Exception ex)
{
try
{
out.close();
in.close();
client.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
private void OnTimeRequst() throws IOException
{
Date d = new Date();
Message msg = new Message();
msg.message = d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
out.writeObject(msg);
}
private void OnDateRequst() throws IOException
{
Date d = new Date();
Message msg = new Message();
msg.message = d.toString() + "";
out.writeObject(msg);
}
}
Server code
import java.net.ServerSocket;
import java.util.ArrayList;
public class Server {
ServerSocket server;
ArrayList<CentralizedServer> list = new ArrayList<>();
public Server()
{
try
{
server = new ServerSocket(5050);
while (true)
{
CentralizedServerthr = new CentralizedServer(server.accept());
list.add(thr);
thr.start();
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
public static void main(String... args) {
new Server();
}
}
You can design this one of two ways.
Option 1: Redirect. The centralized server sends back a response to the client to "redirect" him to server1. (ala http 30x response). Then the client just makes a separate connection to server1 and resends the request.
Option 2: Proxy. Upon receiving the request from the client, the centralized server makes a connection to server1 and sends the request on behalf of the client. When the centralized server receives the response from server1, it just forwards the response to the client.
The redirect method is simpler, but not always possible if "server1" is meant to be protected from direct client access or only accessible from other servers.
The proxy method is a bit harder, but allows for different designs.

Sockets - Server getting stuck on in.readLine() - Java

I've recently been playing around with Sockets in Java but I came across a problem. The server get's stuck in the Server readLine(); I have no clue what is going on, if anyone can help that would be great. I know that the problem is not that readLine() only returns when there is a new line character, but I am using println() not just print().
Here is my current code:
Server Class:
package packets.sidedcomputer;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import packets.Packet;
import packets.data.PacketData;
import packets.info.ClientInfo;
import packets.reciever.PacketReciever;
import packets.sender.PacketSender;
import packets.side.Side;
public class Server extends SidedComputer
{
volatile boolean finished = false;
public ServerSocket serverSocket;
public volatile List<ClientInfo> clients = new ArrayList<ClientInfo>();
public void stopServer()
{
finished = true;
}
public Server()
{
try
{
serverSocket = new ServerSocket(10501);
}
catch (IOException e)
{
e.printStackTrace();
}
}
#Override
public void run()
{
try
{
while (!finished)
{
Socket clientSocket = serverSocket.accept();
if(clientSocket != null)
{
ClientInfo clientInfo = new ClientInfo(clientSocket);
this.clients.add(clientInfo);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String dataString = in.readLine();
while(dataString != null && !dataString.equals(""))
{
PacketReciever packetReciever = new PacketReciever();
PacketData packetData = new PacketData();
packetData.decodeInto(dataString);
Packet packet = packetReciever.recievePacket(packetData, packetData.packetID, getSide(), clientSocket.getLocalAddress().getHostAddress().toString(), clientSocket.getLocalPort() + "");
PacketSender packetSender = new PacketSender();
for (ClientInfo client : this.clients)
{
PrintWriter out = new PrintWriter(client.socket.getOutputStream(), true);
packetSender.sendPacketToClient(packet, out);
}
dataString = in.readLine();
}
serverSocket.close();
}
}
}
catch (Exception e)
{
e.printStackTrace();
System.exit(1);
}
}
#Override
public Side getSide()
{
return Side.SERVER;
}
}
My Client Class:
package packets.sidedcomputer;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
import packets.MessagePacket;
import packets.sender.PacketSender;
import packets.side.Side;
public class Client extends SidedComputer
{
volatile boolean finished = false;
volatile String username;
volatile Server server;
public Socket clientSocket;
public ClientReciever reciever;
public Client(Server server, String username) throws UnknownHostException, IOException
{
this.username = username;
this.server = server;
this.reciever = new ClientReciever(this);
}
public void stopClient()
{
finished = true;
}
#Override
public void run()
{
Scanner scanner = new Scanner(System.in);
reciever.start();
while(!finished)
{
try
{
this.clientSocket = new Socket("192.168.1.25", 10501);
String line;
while((line = scanner.nextLine()) != null)
{
PacketSender sender = new PacketSender();
sender.sendPacket(new MessagePacket(line, username), clientSocket.getLocalAddress().getHostAddress().toString(), "" + clientSocket.getPort());
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
scanner.close();
}
#Override
public Side getSide()
{
return Side.CLIENT;
}
}
My packet sender class:
package packets.sender;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import packets.Packet;
import packets.data.PacketData;
public class PacketSender implements IPacketSender
{
#Override
public void sendPacket(Packet packet, String host, String port)
{
if(packet.getDefualtID() == 0)
{
PacketData packetData = new PacketData(packet.getDefualtID());
packet.writeData(packetData);
String data = packetData.encodeIntoString();
sendData(host, port, data);
}
}
protected void sendData(String hostName, String port, String data)
{
try
{
try
(
Socket socket = new Socket(hostName, Integer.parseInt(port));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
)
{
out.println(data);
}
catch (UnknownHostException e)
{
System.err.println("Don't know about host " + hostName);
System.exit(1);
}
catch (IOException e)
{
System.err.println("Couldn't get I/O for the connection to " + hostName);
System.exit(1);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
public void sendPacketToClient(Packet packet, PrintWriter out)
{
PacketData packetData = new PacketData(packet.getDefualtID());
packet.writeData(packetData);
String data = packetData.encodeIntoString();
out.println(data);
}
}
Here's what's happening
From your client:
this.clientSocket = new Socket("192.168.1.25", 10501);
When this line runs, the server will be woken up from the accept line. And block again at readLine()
Meanwhile, your client, goes through your PacketSender. What does your PacketSender do?
Socket socket = new Socket(hostName, Integer.parseInt(port));
This opens a new connection! So your Client is waiting for the server to accept a connection. And the server is waiting for the client to send a message! You arrive at a deadlock.
Here's how to fix it
remove the following line.
this.clientSocket = new Socket("192.168.1.25", 10501);
then pass the host address and port manually into your PacketSender.

Multiple client server in which a client can only send message to server but server to all clients in java

I want that message sent by server should be delivered to all the clients however a message sent by by client should only be delivered to server.
Problem is when i run the code-
1.Server waits for client to connect
2.when multiple client connected
3.Now as the server broadcast the first message it is received by both the clients but when server broadcast the message second time. Both the clients has to send message in order to receive server message.
I am a noob in socket programming so please correct me what i am doing wrong?
So far i have made this program.
Server Code:
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Scanner;
import java.net.*;
import java.io.*;
public class Server_Side3
{
static Client_server t[] = new Client_server[10];
static LinkedList<Client_server> al = new LinkedList<Client_server>();
public static void main(String args[]) throws IOException
{
ServerSocket server = null ;
Socket socket = null;
try
{
int Port =9777;
server = new ServerSocket(Port);
System.out.println("Waiting for Client " + server);
while(true)
{
socket = server.accept();
System.out.println("Connected to " + socket.getLocalAddress().getHostAddress());
Client_server clients = new Client_server(socket);
al.add(clients);
clients.start();
}
}
catch (Exception e)
{
System.out.println("An error occured.");
e.printStackTrace();
}
try
{
server.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
private static class Client_server extends Thread
{
Socket sockets;
PrintWriter out;
Client_server t[];
Client_server (Socket s )
{
sockets = s;
}
public void run()
{
try
{
InetAddress localaddr = InetAddress.getLocalHost();
Scanner sc = new Scanner(System.in);
Scanner in = new Scanner(sockets.getInputStream());
out = new PrintWriter(sockets.getOutputStream(),true);
String input = null;
while(true)
{
String servermsg = sc.nextLine();
broadcast(servermsg);
System.out.println("Message sent to client: "+servermsg);
input = in.nextLine();
System.out.println(localaddr.getHostName()+" Said :"+ input);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
private void broadcast(String servermsg)
{
Iterator it = al.iterator();
while(it.hasNext())
{
((Client_server) it.next()).send(servermsg);
}
}
private void send(String msg)
{
String servrmsg = msg;
out.println(msg);
out.flush();
}
}
}
Client Code :
import java.net.Socket;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;
public class ClientSide2
{
static Scanner chat = new Scanner(System.in);
public static void main(String[] args)
{
int Port = 9777;
String Host = "localhost";
try
{
Socket socket = new Socket(Host, Port);
System.out.println("You connected to "+ Host);
Scanner in = new Scanner(socket.getInputStream()); //GET THE CLIENTS INPUT STREAM
PrintWriter out = new PrintWriter(socket.getOutputStream());
String clientinput;
while(true)
{
System.out.println(in.nextLine());//If server has sent us something .Print it
clientinput=chat.nextLine();
out.println(clientinput); //SEND IT TO THE SERVER
out.flush();
}
}
catch (Exception e)
{
System.out.println("The server might not be up at this time.");
System.out.println("Please try again later.");
}
}
}

Sending an ArrayList<String> from the server side to the client side over TCP using socket?

I'm trying to send one object from the server side socket to the client side socket over TCP. I can't find out where is the problem.
Here is the error I'm getting on the Client side:
java.io.EOFException
at java.io.ObjectInputStream$PeekInputStream.readFully(ObjectInputStream.java:2280)
at java.io.ObjectInputStream$BlockDataInputStream.readShort(ObjectInputStream.java:2749)
at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:779)
at java.io.ObjectInputStream.<init>(ObjectInputStream.java:279)
at ClientSide.main(ClientSide.java:16)
Code for Server side:
import java.io.*;
import java.net.*;
import java.util.ArrayList;
public class ServerSide {
public static void main(String[] args) {
try
{
ServerSocket myServerSocket = new ServerSocket(9999);
Socket skt = myServerSocket.accept();
ArrayList<String> my = new ArrayList<String>();
my.set(0,"Bernard");
my.set(1, "Grey");
try
{
ObjectOutputStream objectOutput = new ObjectOutputStream(skt.getOutputStream());
objectOutput.writeObject(my);
}
catch (IOException e)
{
e.printStackTrace();
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
Code for the Client Side:
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
public class ClientSide {
public static void main(String[] args)
{
try {
Socket socket = new Socket("10.1.1.2",9999);
ArrayList<String> titleList = new ArrayList<String>();
try {
ObjectInputStream objectInput = new ObjectInputStream(socket.getInputStream()); //Error Line!
try {
Object object = objectInput.readObject();
titleList = (ArrayList<String>) object;
System.out.println(titleList.get(1));
} catch (ClassNotFoundException e) {
System.out.println("The title list has not come from the server");
e.printStackTrace();
}
} catch (IOException e) {
System.out.println("The socket for reading the object has problem");
e.printStackTrace();
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Changing from set to add does the trick
ArrayList<String> my = new ArrayList<String>();
my.add("Bernard");
my.add("Grey");
ps. as advised by the others this is not a good idea but, use only for learning

android/java sockets help

Here is my goal. I am designing a server that will spit out data every second. I need to also design a client (on android) that will connect to that server and gather the data that is being sent by the server. I have already wrote up some code for this in java and for the android. However, my experience with java and android is very minimal. I have been having a lot of difficulty with this but have started making progress. I was wondering if everyone could take a look at my code and give some tips on how to best perform this design.
The server will just be constantly spitting out data and the client will connect to the server and then start gathering the data that is being sent.
The data that is being sent is not important. Right now it will just be something random for testing.
Thanks in advance!
THE JAVA SERVER
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class SmartServerSocket {
private ServerSocket server;
private int port = 7777;
public SmartServerSocket() {
try {
server = new ServerSocket(port);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
SmartServerSocket smart = new SmartServerSocket();
smart.handleConnection();
}
public void handleConnection() {
// TODO Auto-generated method stub
System.out.println("Waiting for client message...");
while (true) {
try {
Socket socket = server.accept();
new ConnectionHandler(socket);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
class ConnectionHandler implements Runnable {
private Socket socket;
public ConnectionHandler(Socket socket) {
this.socket = socket;
Thread t = new Thread(this);
t.start();
}
public void run() {
ObjectOutputStream oos = null;
int test = 0;
try {
while(true)
{
oos = new ObjectOutputStream(socket.getOutputStream());
oos.writeObject(Integer.toString(test));
test++;
System.out.println("Waiting for client message...");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
oos.close();
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
THE ANDROID CLIENT
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
//import android.app.Activity;
public class ConnectDevice implements Runnable {
public void run(){
try {
System.out.println("test1");
//InetAddress host = InetAddress.getLocalHost();
InetAddress host = InetAddress.getByName("THEIPADDRESS");
Socket socket = new Socket(host.getHostName(), 7777);
System.out.println("test2");
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
System.out.println("test3");
String message = (String) ois.readObject();
System.out.println("test4");
System.out.println("Message: " + message);
ois.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
I'm using Apache Mina to handle my game's connection. You should take a look on it. It have really made my life easier.

Categories

Resources