Sending objects to localhost server using java? - java

How do I create a .ser file or write objects to a .ser file in a localhost server?
The following code can read .ser file :
public Object deserialize(InputStream is) {
ObjectInputStream in;
Object obj;
try {
in = new ObjectInputStream(is);
obj = in.readObject();
in.close();
return obj;
} catch (IOException ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
}
URL url;
URLConnection urlConn;
DataInputStream dis;
//url = new URL("http://localhost/Person.ser");
urlConn = url.openConnection();
urlConn.setDoInput(true);
urlConn.setUseCaches(false);
Person person = (person) deserialize(urlConn.getInputStream());
Do I need any server side program to receive the object and store in the file?

you can write to .ser file using following way:
try {
FileOutputStream fos = new FileOutputStream("Filename.ser");
ObjectOutputStream out = new ObjectOutputStream(fos);
out.write(obj);
fos.close();
out.close();
} catch (IOException ex) {}
UPDATE
To read the object at server side you need to create ObjectInputStream wrappint the inputStream of socket via which it is interacting with client . It can be done as follows:
try
{
Socket s = serverSocket.accept();
ObjectInputStream oin = new ObjectInputStream(s.getInputStream());
Object obj = oin.readObject();
oin.close();
}catch(Exception ex){}
OK here is the complete example where I am sending an ArrayList to Server.
Client.java
import java.net.*;
import java.io.*;
import java.util.*;
public class Client
{
public static void main(String[] args)
{
Socket s = null;
ObjectOutputStream out = null;
System.out.println("Connecting to Server ...");
try
{
s = new Socket("localhost", 1401);
out = new ObjectOutputStream (s.getOutputStream());
ArrayList<String> list = ArrayList<String> list = new ArrayList<String>();
for (int i = 0; i < 10 ; i++)
{
list.add("String"+i);
}
out.writeObject(list);out.flush();
System.out.println("ArrayList sent to Server");
} catch ( Exception e)
{
e.printStackTrace();
}
finally
{
if (out!= null)
{
try
{
out.close();
}
catch (Exception ex){}
}
if (s != null)
{
try
{
s.close();
}
catch (Exception ex){}
}
}
}
}
Server.java
import java.net.*;
import java.io.*;
import java.util.*;
public class Server
{
public static void main(String[] args)
{
ObjectInputStream oin = null;
ServerSocket server;
Socket socket = null;
try
{
server = new ServerSocket(1401);
socket = server.accept();
System.out.println("Client Connected..Sending ArrayList to Client");
oin = new ObjectInputStream(socket.getInputStream());
ArrayList<String> list = (ArrayList<String>)oin.readObject();
System.out.println("Recieved ArrayList from client "+list);
//Writing to file now
FileOutputStream fos = new FileOutputStream("Filename.ser");
ObjectOutputStream out = new ObjectOutputStream(fos);
out.write(obj);
fos.close();
out.close();
System.out.println("Written to file");
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
if (oin != null)
{
try
{
oin.close();
}
catch (Exception ex){}
}
if (socket != null)
{
try
{
socket.close();
}
catch (Exception ex){}
}
}
}
}

Related

Multi Client chat Server Java

i am coding a multi client chat server.i have a server folder that contains Server.java and three client folders namely client1,client2,client3 containing java files resp.now when every client joins the server i try to send a text but the server does not picks the message.the problem is in the void run() try method. till the while(true) loop everything works.
Server code:
Chat.java
import java.net.*;
import java.io.*;
import java.util.*;
class Chat implements Runnable {
Socket skt = null;
DataInputStream dis = null;
DataOutputStream dos = null;
PrintWriter pw = null;
TreeMap<Socket, String> tm;
public Chat(Socket skt, TreeMap<Socket, String> tm) {
this.skt = skt;
this.tm = tm;
}
public void run() {
try {
dis = new DataInputStream(skt.getInputStream());
String msg = "";
while (true) {
msg = dis.readUTF();
Set s = tm.keySet();
Iterator itr = s.iterator();
while (itr.hasNext()) {
String k = (String) itr.next();
Socket v = (Socket) tm.get(k);
dos = new DataOutputStream(v.getOutputStream());
dos.writeUTF();
}
}
} catch (Exception e) {
System.out.println(e);
} finally {
try {
dis.close();
} catch (Exception ex) {
System.out.println(ex);
}
}
}
}
Server.java
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.TreeMap;
class Server
{
public static void main(String dt[])
{
ServerSocket sskt=null;
Socket skt=null;
DataInputStream dis=null;
DataOutputStream dos=null;
TreeMap <String,Socket>tm=new TreeMap<String,Socket>();
try
{
sskt=new ServerSocket(1234);
System.out.println("Waiting for Clients");
while(true)
{
skt=sskt.accept();
dis=new DataInputStream(skt.getInputStream());
dos=new DataOutputStream(skt.getOutputStream());
String user=dis.readUTF();
String pass=dis.readUTF();
if(user.equals(pass))
{
dos.writeBoolean(true);
tm.put(user,skt);
Chat ch=new Chat(skt,tm);
Thread t=new Thread(ch);
t.start();
}
else
{
dos.writeBoolean(false);
}
} //end of while.
}
catch(Exception e)
{
System.out.println(e);
}
finally
{
try
{
dos.close();
dis.close();
skt.close();
sskt.close();
}
catch(Exception ex)
{
System.out.println(ex);
}
}
}
}
Client Code:
Send.java
import java.io.*;
import java.net.*;
class Send implements Runnable {
Socket skt = null;
public Send(Socket skt) {
this.skt = skt;
System.out.println(skt);
}
public void run() {
InputStreamReader isrout = null;
BufferedReader brout = null;
PrintWriter pw = null;
DataInputStream dis = null;
try {
// Thread.sleep(2000);
System.out.println("Send a text");
isrout = new InputStreamReader(System.in);
brout = new BufferedReader(isrout);
pw = new PrintWriter(skt.getOutputStream(), true);
do {
String msg = brout.readLine();
pw.println(msg);
} while (!msg.equals("bye"));
} catch (Exception e) {
System.out.println(e);
} finally {
try {
pw.close();
brout.close();
isrout.close();
} catch (Exception ex) {
System.out.println(ex);
}
}
}
}
Client1.java
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.Socket;
class Client1 {
public static void main(String dt[]) {
Socket skt = null;
InputStreamReader isr = null;
BufferedReader br = null;
DataOutputStream dos = null;
DataInputStream dis = null;
try {
skt = new Socket("127.0.0.1", 1234);
System.out.println("Connected to server");
System.out.println(skt);
isr = new InputStreamReader(System.in);
br = new BufferedReader(isr);
dos = new DataOutputStream(skt.getOutputStream());
dis = new DataInputStream(skt.getInputStream());
System.out.println("Enter a username");
String user = br.readLine();
dos.writeUTF(user);
System.out.println("Enter a password");
String pass = br.readLine();
dos.writeUTF(pass);
if (dis.readBoolean()) {
System.out.println("User Authenticated");
} else {
System.out.println("Incorrect username or password");
}
Send sn = new Send(skt);
Thread t = new Thread(sn);
t.start();
} catch (Exception e) {
System.out.println(e);
} finally {
try {
// skt.close();
} catch (Exception ex) {
System.out.println(ex);
}
}
}
}
After writing any value using an outputstream you need to flush it to actually send it.
In the Chat and Server class where you use DataOutputStream, you need to call this after writing data.
dos.flush();
In the Client class after sending data through the PrintWriter you need to call this.
pw.flush();

Socket programming.sending files

I'm trying to send a file between server and client but when I'm trying to write into socket I'm getting java.net.SocketException: Connection reset by peer: socket write error.
//server side
package tcp;
import java.net.*;
import java.io.*;
import java.sql.Connection;
import java.util.*;
public class ServerSock {
static ServerSocket Socket1;
static int port=2500;
public static void main(String[] args) {
Socket server;
File filename=new File("C:/Users/Sudhir/Desktop/mot.wmv");
byte[] serverBuffer=new byte[(int)filename.length()];
StringBuffer msgFromClient= new StringBuffer();
String timeStamp;
try {
Socket1=new ServerSocket(port);
System.out.println("Server Socket is initialised");
int c;
server=Socket1.accept();
BufferedInputStream serverInputBuffer = new BufferedInputStream(server.getInputStream());
InputStreamReader serverInputStream = new InputStreamReader(serverInputBuffer);
while((c=serverInputStream.read())!=13) {
msgFromClient.append((char)c);
}
System.out.println(msgFromClient);
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
timeStamp=new Date().toString();
//String filename = "test.pdf";
//byte[] serverBuffer=new byte[1024*33];
String respond = "Server responded at "+ timeStamp + (char) 13;
//System.out.println(respond);
//BufferedOutputStream bos = new BufferedOutputStream(server.getOutputStream());
//OutputStreamWriter osw = new OutputStreamWriter(bos);
FileInputStream fis=new FileInputStream(filename);
BufferedInputStream bis = new BufferedInputStream(fis);
bis.read(serverBuffer,0,serverBuffer.length);
OutputStream os=server.getOutputStream();
try{
os.write(serverBuffer,0,serverBuffer.length);
}catch(IOException e2){
System.out.println(e2);
}
//String serverMessage=new String(serverBuffer);
//serverMessage+=(char)13;
//osw.write(respond);
os.flush();
server.close();
} catch (IOException e){
e.printStackTrace();
}
}
}
//clientside
package tcp;
import java.io.*;
import java.net.*;
import java.util.*;
public class ClientSocket {
public static void main(String[] args) {
String host="127.0.0.1";
int port=2500;
StringBuffer msgFromServer = new StringBuffer();
String timeStamp;
byte clientBuffer[]=new byte[732419705];
System.out.println("Client Socket is initialised");
try {
InetAddress serverAddress=InetAddress.getByName(host);
try {
Socket clientSocket=new Socket(serverAddress,port);
BufferedOutputStream clientOutputBuffer = new BufferedOutputStream(clientSocket.getOutputStream());
OutputStreamWriter clientOutputStream = new OutputStreamWriter(clientOutputBuffer);
timeStamp=new Date().toString();
String clientMessage="Calling Server on "+host +" port" +port +" at" +timeStamp + (char)13;
clientOutputStream.write(clientMessage);
clientOutputStream.flush();
//BufferedInputStream clientInputBuffer= new BufferedInputStream(clientSocket.getInputStream());
//InputStreamReader clientInputStream = new InputStreamReader(clientInputBuffer);
int c;
try {
Thread.sleep(3000);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// while((c=clientInputStream.read())!=13){
// msgFromServer.append((char)c);
//}
FileOutputStream fos=new FileOutputStream("C:/Users/Sudhir/Desktop/sud.wmv");
BufferedOutputStream bos = new BufferedOutputStream(fos);
InputStream is = clientSocket.getInputStream();
int readbytes=is.read(clientBuffer,0,clientBuffer.length);
bos.write(clientBuffer,0,readbytes);
//System.out.println(msgFromServer);
//System.out.println("end");
bos.close();
clientSocket.close();
} catch (IOException e) {
System.out.println(e);
}
} catch (UnknownHostException e) {
System.out.println(e);
}
}
}

Java program to read objects from a .ser file located in a server

My idea is that I want to read an object from a serialized file located in a server. How to do that?
I can only read .txt file using the following code :
void getInfo() {
try {
URL url;
URLConnection urlConn;
DataInputStream dis;
url = new URL("http://localhost/Test.txt");
// Note: a more portable URL:
//url = new URL(getCodeBase().toString() + "/ToDoList/ToDoList.txt");
urlConn = url.openConnection();
urlConn.setDoInput(true);
urlConn.setUseCaches(false);
dis = new DataInputStream(urlConn.getInputStream());
String s;
while ((s = dis.readLine()) != null) {
System.out.println(s);
}
dis.close();
} catch (MalformedURLException mue) {
System.out.println("Error!!!");
} catch (IOException ioe) {
System.out.println("Error!!!");
}
}
You can do this with this method
public Object deserialize(InputStream is) {
ObjectInputStream in;
Object obj;
try {
in = new ObjectInputStream(is);
obj = in.readObject();
in.close();
return obj;
}
catch (IOException ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
catch (ClassNotFoundException ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
}
feed it with urlConn.getInputStream() and you'll get the Object. DataInputStream is not fit to read serialized objets that are done with ObjectOutputStream. Use ObjectInputStream respectively.
To write an object to the file there's another method
public void serialize(Object obj, String fileName) {
FileOutputStream fos;
ObjectOutputStream out;
try {
fos = new FileOutputStream(fileName);
out = new ObjectOutputStream(fos);
out.writeObject(obj);
out.close();
}
catch (IOException ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
}

Socket connection closed unexpectedly

So I'm just testing out some client-server stuff (I was working on it in a larger project but it kept throwing errors, so I decided to make sure I was doing it right. Turns out I wasn't)
which involves ObjectOutput and Input streams. It works perfectly when I run client and server on localhost, but if I run server on my linux server and client on my computer, the connection has reset by the time I reach the line where the object is fetched. Here's the code:
Client:
public static void main(String[] args){
String[] stuff = {"test", "testing", "tester"};
Socket s = null;
ObjectOutputStream oos = null;
try {
s = new Socket("my.server.website", 60232);
oos = new ObjectOutputStream(s.getOutputStream());
oos.writeObject(stuff);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{
try {
s.close();
oos.close();
} catch (IOException e) {}
}
}
Server:
public static void main(String[] args){
ServerSocket ss = null;
Socket s = null;
ObjectInputStream ois = null;
try {
ss = new ServerSocket(60232);
s = ss.accept();
System.out.println("Socket Accepted");
ois = new ObjectInputStream(s.getInputStream());
Object object = ois.readObject();
System.out.println("Object received");
if (object instanceof String[]){
String[] components = (String[]) object;
for (String string : components){
System.out.println(string);
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}finally{
try {
ss.close();
s.close();
ois.close();
} catch (IOException e) {}
}
}
In the client, you are closing the underlying socket s before closing your output stream.
Try this:
try {
oos.close();
s.close();
} catch (IOException e) {}
The oos.close() should cause the object output stream to flush all it's data to the socket and then close the object stream. Then you can close the underlying socket.

Java Chat System

I'm having problems with broadcasting the messages sent by each client. The server can receive each message from multiple clients but it cannot broadcast it. Error message says connection refused
Client:
public void initializeConnection(){
try {
host = InetAddress.getLocalHost();
try{
// Create file
FileWriter fstream = new FileWriter("src/out.txt", true);
BufferedWriter out = new BufferedWriter(fstream);
out.write(host.getHostAddress()+'\n');
//Close the output stream
out.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
clientSocket = new Socket(host.getHostAddress(), port);
outToServer = new PrintWriter(clientSocket.getOutputStream(), true);
inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
}
catch(IOException ioEx) {
ioEx.printStackTrace();
}
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==quit){
try {
outToServer.close();
clientSocket.close();
System.exit(1);
} catch (IOException e1) {
e1.printStackTrace();
}
}
else if(e.getSource()==button){
if(outMsgArea.getText()!=null || !outMsgArea.getText().equals("")){
String message = outMsgArea.getText();
outToServer.println(clientName+": "+message);
outMsgArea.setText("");
}
}
}
public void run(){
try {
while(true){
String message = inFromServer.readLine();
System.out.println(message);
inMsgArea.append(message+'\n');
}
} catch (IOException e) {
e.printStackTrace();
}
}
Server:
import java.io.*;
import java.net.*;
import java.util.*;
public class RelayChatServer {
public static int port = 44442;
ServerSocket server;
public void listenSocket(){
try{
server = new ServerSocket(port);
} catch (IOException e) {
System.out.println("Could not listen on port 4444");
System.exit(-1);
}
while(true){
ClientWorker w;
try{
//server.accept returns a client connection
w = new ClientWorker(server.accept());
Thread t = new Thread(w);
t.start();
} catch (IOException e) {
System.out.println("Accept failed: 4444");
System.exit(-1);
}
}
}
protected void finalize(){
//Objects created in run method are finalized when
//program terminates and thread exits
try{
server.close();
} catch (IOException e) {
System.out.println("Could not close socket");
System.exit(-1);
}
}
public static void main(String[] args) {
new RelayChatServer().listenSocket();
}
}
class ClientWorker implements Runnable {
private Socket client;
//Constructor
ClientWorker(Socket client) {
this.client = client;
}
public void run(){
String line;
BufferedReader in = null;
PrintWriter out = null;
try{
in = new BufferedReader(new
InputStreamReader(client.getInputStream()));
//out = new
// PrintWriter(client.getOutputStream(), true);
} catch (IOException e) {
System.out.println("in or out failed");
System.exit(-1);
}
while(true){
try{
line = in.readLine();
//Send data back to client
//out.println(line);
//Append data to text area
if(line!=null && line!=""){
System.out.println(line);
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("out.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
//Read File Line By Line
Socket s;
PrintWriter prnt;
while ((strLine = br.readLine()) != null && (strLine = br.readLine()) != "") {
// Print the content on the console
s = new Socket(strLine, 44441);
prnt = new PrintWriter(s.getOutputStream(),true);
prnt.println(line);
System.out.println(strLine);
prnt.close();
s.close();
}
//Close the input stream
//inp.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}catch (IOException e) {
System.out.println("Read failed");
e.printStackTrace();
System.exit(-1);
}
}
}
}
The Exception starts:
java.net.ConnectException: Connection refused: connect
The expanded output looks like:
I'm somewhat confused as to why you attempt to open a new socket (do you intend for this to be sent back to the client?) based on a string you read from a file. Perhaps
s = new Socket(strLine, 44441);
prnt = new PrintWriter(s.getOutputStream(),true);
should be:
prnt = new PrintWriter(client.getOutputStream(),true);
As currently I don't see where you are sending anything back to the client.
Edit: ok try something like the following:
static final ArrayList<ClientWorker> connectedClients = new ArrayList<ClientWorker>();
class ClientWorker implements Runnable {
private Socket socket;
private PrintWriter writer;
ClientWorker(Socket socket) {
this.socket = socket;
try {
this.writer = new PrintWriter(socket.getOutputStream(), true);
} catch (IOException ex) { /* do something sensible */ }
}
public void run() {
synchronized(connectedClients) {
connectedClients.add(this);
}
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (IOException e) { /* do something sensible */ }
while (true) {
try {
String line = in.readLine();
if (line != null && line != "") {
synchronized (connectedClients) {
for (int i = 0; i < connectedClients.size(); ++i){
ClientWorker client = connectedClients.get(i);
client.writer.println(line);
}
}
}
} catch (IOException e) { /* do something sensible */ }
}
}
}

Categories

Resources