I want to send an object(array) from a client to a server. I use the ObjectInputStream and the ObjectOutputStream. However, this invokes an error, that these methods are not defined in serverSocket class.
How do I resolve the situation ??`
public int[] readResponse() throws IOException, ClassNotFoundException{
int[] x = new int[5];
ObjectOutputStream cO = new ObjectOutputStream(serverSocket.getOutputStream()); //here is the error
ObjectInputStream cI = new ObjectInputStream(serverSocket.getInputStream()); // here is the error
cO.writeObject(x);
x = (int[]) cI.readObject();
for (int i = 0; i < 5; i++){
System.out.println(x[i]);
}
return x;
}
A java.net.ServerSocket is not meant to be used for actual input and output; it is a socket for listening on the server to incoming connection requests which are accepted, resulting in a java.net.Socket which is then the one for reading and writing.
Socket socket = serverSocket.accept();
ObjectInputStream cI =
new ObjectInputStream(socket.getInputStream());
On the client side, a java.net.Socket is created by calling the constructor and connected, via an address, to the client.
Socket socket = new Socket( address, port );
ObjectOutputStream cO =
new ObjectOutputStream(socket.getOutputStream());
Related
I am developing server-client side java program, where I have sliced an jpg image using getSubimage() and saved into int image[][][]
The class below initialises connection with the server and receives an array, however compiler states that readObject() is undifined. Any suggestions how to fix this problem?
Thanks!
public void con() throws IOException {
int port = 7676;
ObjectInputStream inputStream = null;
Socket socket = null;
// try to establish the connection to the server
try {
socket = new Socket(hostName, port);
InputStreamReader is = new InputStreamReader(socket.getInputStream());
int pixels[][][] = new int[20][20][400];
pixels = (int[][][])is.readObject();
}
it must be of type ObjectInputStream, so you should write something like this:
pixels = (int[][][])inputStream.readObject();
where inputStream is type of ObjectInputStream.
i have a simple server...
public static void main(String[] args) throws Exception{
ServerSocket server = new ServerSocket(2000);
Socket sock = server.accept();
InputStream in = sock.getInputStream();
OutputStream out = sock.getOutputStream();
PrintWriter w = new PrintWriter(out);
Scanner s = new Scanner(in);
...
and a simple client...
public static void main(String[] args) throws Exception{
Socket sock = new Socket("localhost",2000);;
InputStream in= sock.getInputStream();
OutputStream out = sock.getOutputStream();
PrintWriter w = new PrintWriter(out);
Scanner s = new Scanner(in);
....
-how can i connect more clients to this server? (I need 2 more)
-also i want to send system time from server to clients and then clients will send
back their time 10 times each plus some fixed delay (0.5-1 sec) then the server must find the average from all delays and send it back to the clients as the new time...
thank you for your time...
System.currentTimeMillis() provides the system time
Every Socket returned by server.accept() is a separate object and your server can communicate independently with each client through each Socket object. However, since your application is time-sensitive, I would recommend using a separate thread for each client.
A simple server would be:
ServerSocket serverSock = new ServerSocket(2000);
while (true)
{
Socket fpSock = serverSock.accept();
MyThread t = new MyThread(fpSock, this);
t.start();
}
The processing you need will be done in the MyThread run() method. "this" is passed to the thread to provide a reference where each thread can callback to methods in the main class. Make sure to make such methods synchronized.
You also don't necessarily need to send the server's time to the client, simply send a generic packet which the client is expected to echo back. Use the server's timestamp for all transactions to avoid variation in client system time.
I have an interesting question. I am trying to establish a peer to peer connection which means a client process acts both as a server and client. Ideally, it should have a client socket (Socket class) and a server socket(Server Socket class). Now I tried to use this concept but it does not work. Please take a look at it:
public static void main(String argv[]) throws Exception
{
Socket clientSocket = null;
BufferedReader inFromUser = new BufferedReader( new InputStreamReader(System.in));
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
System.out.println("Enter the server port u want to be assigned to this peer:");
sentence = inFromUser.readLine();
System.out.println("writing current port to client = "+ sentence);
outToServer.writeBytes("p~"+sentence + "\n" );
int serverport = Integer.parseInt(sentence);
ServerSocket server = new ServerSocket(serverport);
Socket client;
//client
System.out.println("enter port no of the server port of an other peer:");
int msg=Integer.parseInt(inFromUser.readLine());
clientSocket = new Socket("localhost", msg);
outToServer = new DataOutputStream(clientSocket.getOutputStream());
outToServer.writeBytes("hi");
while(true)
{
//server port listens infinitely and spawns new thread
System.out.println("inside true");
client = server.accept();
Thread serverThread = new Thread(new acceptconnection1(client));
serverThread.start();
}}}
class acceptconnection1 implements Runnable {
BufferedReader inFromClient, inn;
DataOutputStream ds;
Socket socket;
int peersocket;
String clientSentence;
int serverport ;
Socket clientSocket = null;
acceptconnection1 (Socket socket,) throws IOException{
this.socket = socket;
inn = new BufferedReader (new InputStreamReader(System.in));
inFromClient =new BufferedReader(new InputStreamReader(socket.getInputStream()));
ds = new DataOutputStream(socket.getOutputStream());
}
#Override
public void run () {
String cs,a;
try {
System.out.println("waiting for connection ");
if(( clientSentence = inFromClient.readLine())!=null)
{
System.out.println("Message from other peer" + clientSentence);
}
} catch (IOException ex) {
Logger.getLogger(acceptconnection1.class.getName()).log(Level.SEVERE, null, ex);
}}}
Output:
when I create two client processes,
o/p of client1:
Enter the server port u want to be assigned to this peer:
1111
writing current port to client = 1111
hi enter port no u want to connect to:
2222
inside true
inside true
waiting for connection
Enter the server port u want to be assigned to this peer:
2222
writing current port to client = 2222
hi enter port no u want to connect to:
1111
inside true
inside true
waiting for connection
what happens is both of them wait for connections. how do i solve this?
You have a deadlock condition. To result this, create the ServerSocket first so the Socket has something to talk to. Create the Socket which will connect but do nothing until accepted. Then accept connections.
BTW: You don't need to create two connections for traffic to pass both ways. Once a connection has been established, you can use that one connection as client-server, or server-server or what ever.
I've got question, that I haven't found answer for yet. I have 2 devices with wifi each, that are sending special data. I want to show this data at the same moment on a tablet. There is a router with network, both tablet and that devices are connected to this network.
How to solve this? Should I use serversocket? I don't know if I explained it clear enought, if not, please ask. Thanks for any response.
I have the same application running on the company I work.
The "device" is a micro-controller based device that is implemented the lwIP (lightweight IP protocol) and it's listening to the port 83 and every 500ms the tablet goes and read new fresh data and plot it in a graph. Works like a charm.
(in case you'll be plotting charts, I used the AChartEngine and you can check on my profile a question/answer on it with some useful info)
the code below is a simplified version of what I'm doing. The complete version includes SEVERAL try{ } catch() { } in case it catches an exception it try closing the socket and return null;
public static String SendMessage(String message, String ip, int port) {
// Connect to host ==================================
Socket socket = new Socket();
socket.setSoTimeout(TIMEOUT);
InetSocketAddress addr = new InetSocketAddress(ip, port);
socket.connect(addr, TIMEOUT);
// Send Message ======================================
byte[] outputBuffer = message.getBytes();
socket.getOutputStream().write(outputBuffer);
// Zero the input buffer =============================
for (int i = 0; i < inputBuffer.length; i++) {
inputBuffer[i] = 0;
}
// Read the response ==================================
int count = 0;
do {
count = socket.getInputStream().read(inputBuffer);
} while (count != -1);
// Close connection ====================================
close(socket);
// Return message ======================================
return new String(inputBuffer).trim();
}
hope it helps,
happy coding.
1. Socket will be a good idea.
For Sending :
Socket s = new Socket();
s.connect(new InetSocketAddress("IP_ADDR",PORT_NO);
OutputStream o = s.getOutputStream();
PrintWriter pw = new PrintWriter(o);
pw.write(msg); // msg will be the data needed to send
For Receiving:
Socket s = new Socket();
s.connect(new InetSocketAddress("IP_ADDR",PORT_NO);
InputStream i = s.getInputStream();
InputStreamReader isr = new InputStreamReader(i);
BufferedReader br = new BufferedReader(isr);
String str = new String();
while((str=br.readLine())!=null){
System.out.println(str); // do whatever u want to do with str, the data read
}
I develop a client-server java application and I used ObjectOutputStream and ObjectInputStream to send and receive data between client and server process. I need to send Array or object or primitive data
but the problem appears when I use ObjectOutputStream and ObjectInputStream to send and receive primitive values ( writeDouble(), readDouble(), writeUTF(), readUTF() ) . the program suspended and stopped working. why, what is the problem?
these are a fragments of my program
// client program
ObjectOutputStream toServer;
ObjectInputStream fromServer;
// Establish connection with the server
Socket socket = new Socket(host, 7000);
// Create an output stream to the server
toServer = new ObjectOutputStream(socket.getOutputStream());
fromServer = new ObjectInputStream(socket.getInputStream());
double num1 = Double.parseDouble(jtf1.getText().trim());
double num2 = Double.parseDouble(jtf2.getText().trim());
try {
toServer.writeUTF("multiply");
toServer.writeDouble(num1);
toServer.writeDouble(num2);
double result = fromServer.readDouble();
res.setText(String.valueOf(result));
} catch (IOException ex) {
System.err.println(ex);
}
// server program
private ObjectOutputStream outputToClient;
private ObjectInputStream inputFromClient;
// Create a server socket
ServerSocket serverSocket = new ServerSocket(7000);
while (true) {
// Listen for a new connection request
Socket socket = serverSocket.accept();
System.out.println("connect ");
outputToClient = new ObjectOutputStream(socket.getOutputStream());
// Create an input stream from the socket
inputFromClient =
new ObjectInputStream(socket.getInputStream());
while(true) {
// Read from input
String command = inputFromClient.readUTF();
System.out.println("receive command");
checkRequest(command);
}
// Write to the file
//outputToFile.writeObject(object);
}
public void checkRequest(String cmd){
//Object o = null;
try{
if(cmd.equals(MULTIBLY)){
double x = inputFromClient.readDouble();
double y = inputFromClient.readDouble();
double result = x*y;
outputToClient.writeDouble(result);
System.out.println("send result");
}else if (cmd.equals(DIVIDE)){
int x = inputFromClient.readInt();
int result = 1000/x;
outputToClient.writeDouble(result);
}
} catch(IOException io){
}
}
when I change ObjectOutputstream and ObjectInputStream to DataOutputStream
and DataInputStream every thing goes correctly !
You must call flush() on the stream on the client side to actually send the data (if the socket's buffer is not full).
You see your program hanging because the client does not send the data, and the server is blocking, waiting for the data that will never come.