Sending 2 objects through sockets?

Hi there,
I have 2 questoins here...
The first is....
Ive made a simple game that moves a image around a screen using the arrow keys. When i start the server it listens for connections and then I run the client. I'm able to get 2 instances of the objects running in 2 different swing frames but at the moment when I move the image around the screen it only moves in one window and not in the other. I would like the coordinates of the image in one window to be the same as the other when I move it.
this is my server class...
  public void run() {
           try {
              oos.writeObject(pgf.getPacmanGamePanel().getPacmanGame());
              oos.writeObject(pgf.getPacmanGamePanel().getGhost());i move the pacmanGame on my PacmanGamePanel(pgp) which is on a pacmanGameFrame(pgf)
This is my Client class....
public static void main(String argv[]) {
            PacmanGameFrame pgf = new PacmanGameFrame();
           ObjectOutputStream oos = null;
           ObjectInputStream ois = null;
           //ObjectInputStream ois2 = null;
           Socket socket = null;
           PacmanGame pacgame = null;
           Ghost ghost = null;
           int port = 4444;
           try {
             // open a socket connection
             socket = new Socket("localhost", port);
             // open I/O streams for objects
             oos = new ObjectOutputStream(socket.getOutputStream());
             ois = new ObjectInputStream(socket.getInputStream());
             //ois2 = new ObjectInputStream(socket.getInputStream());
             while (true) {
                    // read an object from the server
                    pacgame = (PacmanGame) ois.readObject();
                    ghost = (Ghost) ois.readObject();
                    oos.reset();
                    I was hoping you could tell me why its not sending the object over from my client.
The second thing is i've coded a Ghost class the exact same way as my PacmanGame class which contains how the image moves around the screen and its methods etc. For some reason its not displaying at all on either the client or the server when i try to send the object across.
I am trying the same way as sending the pacmanGame() but it doesn't work....
public void run() {
           try {
              oos.writeObject(pgf.getPacmanGamePanel().getPacmanGame());
              oos.writeObject(pgf.getPacmanGamePanel().getGhost());I have a panel class which prints out the coordinates of the ghost
public void paint(Graphics g) {
        super.paint(g);
        if(ingame) {
             Graphics2D g2d = (Graphics2D)g;
            g2d.drawImage(pacmanGame.getImage(), pacmanGame.getX(), pacmanGame.getY(), this);
        for (int i = 0; i < ghosts.size(); i++) {
             Ghost ghost = (Ghost)ghosts.get(i);
             if(ghost.isVisible())
                  g2d.drawImage(ghost.getImage(), ghost.getX(), ghost.getY(), this);
        g2d.setColor(Color.WHITE);
        else {
             System.out.println("GAME OVER");
        Toolkit.getDefaultToolkit().sync();
        g.dispose();
    }Help on either question would be great.
1. why wont the image move on both server and client sides.
2. How can i get my ghost class to display?
If you need more info/code let me know..
Thanks alot.

Ok i called flush() on the output and commented out reset() on the input but still the same problem.
oos.writeObject(pgf.getPacmanGamePanel().getPacmanGame());
              oos.writeObject(pgf.getPacmanGamePanel().getGhost());
              oos.flush();
pacgame = (PacmanGame) ois.readObject();
                    ghost = (Ghost) ois.readObject();I think i've figured it out now and its to do with my paint() within gamePanel..
public class PacmanGamePanel extends JPanel implements ActionListener {
    private Timer timer;
    private PacmanGame pacmanGame;
    private Ghost ghost;
    private ArrayList ghosts;
    private boolean ingame;
    private int B_WIDTH;
    private int B_HEIGHT;
    private int[][] pos = {
              {50, 50}
public void paint(Graphics g) {
        super.paint(g);
        if(ingame) {
             Graphics2D g2d = (Graphics2D)g;
            g2d.drawImage(pacmanGame.getImage(), pacmanGame.getX(), pacmanGame.getY(), this);
        for (int i = 0; i < ghosts.size(); i++) {
             Ghost ghost = (Ghost)ghosts.get(i);
             if(ghost.isVisible())
                  g2d.drawImage(ghost.getImage(), ghost.getX(), ghost.getY(), this);
        g2d.setColor(Color.WHITE);
        else {
             System.out.println("GAME OVER");
        Toolkit.getDefaultToolkit().sync();
        g.dispose();
    }Can you help?

Similar Messages

  • Cannot send and read objects through sockets

    I have these 4 classes to send objects through sockets. Message and Respond classes are just for
    trials. I use their objects to send &#305;ver the network. I do not get any compile time error or runtime error but
    the code just does not send the objects. I used object input and output streams to send and read objects
    in server (SOTServer) and in the client (SOTC) classes. When I execevute the server and client I can see
    that the clients can connect to the server but they cannot send any objects allthough I wrote them inside the main method of client class. This code stops in the run() method but I could not find out why it
    does do that. Run the program by creating 4 four classes.
    Message.java
    Respond.java
    SOTC.java
    SOTServer.java
    Then execute server and then one or more clients to see what is going on.
    Any ideas will be appreciated
    thanks.
    ASAP pls
    //***********************************Message class**********************
    import java.io.Serializable;
    public class Message implements Serializable
    private String chat;
    private int client;
    public Message(String s,int c)
    client=c;
    chat=s;
    public Message()
    client=0;
    chat="aaaaa";
    public int getClient()
    return client;
    public String getChat()
    return chat;
    //*******************************respond class*****************************
    import java.io.Serializable;
    public class Respond implements Serializable
    private int toClient;
    private String s;
    public Respond()
    public Respond(String s)
    this.s=s;
    public int gettoClient()
    return toClient;
    public String getMessage()
    return s;
    //***********************************SOTServer*********************
    import java.io.*;
    import java.net.*;
    import java.util.Vector;
    //private class
    class ClientWorker extends Thread
    private Socket client;
    private ObjectInputStream objectinputstream;
    private ObjectOutputStream objectoutputstream;
    private SOTServer server;
    ClientWorker(Socket socket, SOTServer ser)
    client = socket;
    server = ser;
    System.out.println ("new client connected");
    try
    objectinputstream=new ObjectInputStream(client.getInputStream());
    objectoutputstream=new ObjectOutputStream(client.getOutputStream());
    catch(Exception e){}
    public void sendToClient(Respond s)
    try
    objectoutputstream.writeObject(s);
    objectoutputstream.flush();
    catch(IOException e)
    e.printStackTrace();
    public void run()
    do
    Message fromClient;
    try
    fromClient =(Message) objectinputstream.readObject();
    System.out.println (fromClient.getChat());
    Respond r=new Respond();
    server.sendMessageToAllClients(r);
    System.out.println ("send all completed");
    catch(ClassNotFoundException e){e.printStackTrace();}
    catch(IOException ioexception1)
    ioexception1.printStackTrace();
    break;
    Respond k=new Respond();
    sendToClient(k);
    }while(true);
    public class SOTServer
    ServerSocket server;
    Vector clients;
    public static void main(String args[]) throws IOException
    SOTServer sotserver = new SOTServer();
    sotserver.listenSocket();
    SOTServer()
    clients = new Vector();
    System.out.println ("Server created");
    public void sendMessageToAllClients(Respond str)
    System.out.println ("sendToallclient");
    ClientWorker client;
    for (int i = 0; i < clients.size(); i++)
    client = (ClientWorker) (clients.elementAt(i));
    client.sendToClient(str);
    public void listenSocket()
    try
    System.out.println ("listening socket");
    server = new ServerSocket(4444, 6);
    catch(IOException ioexception)
    ioexception.printStackTrace();
    do
    try
    ClientWorker clientworker=new ClientWorker(server.accept(), this);
    clients.add(clientworker);
    clientworker.start();
    catch(IOException ioexception1)
    ioexception1.printStackTrace();
    while(true);
    protected void finalize()
    try
    server.close();
    catch(IOException ioexception)
    ioexception.printStackTrace();
    //*************************SOTC***(client class)*********************
    import java.io.*;
    import java.net.Socket;
    import java.net.UnknownHostException;
    class SOTC implements Runnable
    private Socket socket;
    private ObjectOutputStream output;
    private ObjectInputStream input;
    public void start()
    try
    socket= new Socket("127.0.0.1",4444);
    input= new ObjectInputStream(socket.getInputStream());
    output= new ObjectOutputStream(socket.getOutputStream());
    catch(IOException e){e.printStackTrace();}
    Thread outputThread= new Thread(this);
    outputThread.start();
    public void run()
    try
    do
    Message m=new Message("sadfsa",0);
    output.writeObject(m);
    Respond fromServer=null;
    fromServer=(Respond)input.readObject();
    }while(true);
    catch(NullPointerException e){run();}
    catch(Exception e){e.printStackTrace();}
    public SOTC()
    start();
    public void sendMessage(Message re)
    try
    Message k=new Message("sdasd",0);
    output.writeObject(k);
    output.flush();
    catch(Exception ioexception)
    ioexception.printStackTrace();
    System.exit(-1);
    public static void main(String args[])
    SOTC sotclient = new SOTC();
    try
    System.out.println("client obje sonrasi main");
    Message re=new Message("client &#305;m ben mesaj bu da iste",0);
    sotclient.sendMessage(re);
    System.out.println ("client gonderdi mesaji");
    catch(Exception e) {e.printStackTrace();}

    ObjectStreams send a few bytes at construct time. The OutputStream writes a header and the InputStram reads them. The InputStream constrcutor will not return until oit reads that header. Your code is probably hanging in the InputStream constrcutor. (try and verify that by getting a thread dump)
    If that is your problem, tolution is easy, construct the OutputStreams first.

  • Send a message through socket

    Hi
    I want to send a MIMEMessage through socket. And want to receive the same.
    Could any one help me out ?

    Hi
    I proceed that thing.
    I am getting the problem while converting the input stream from socket to MIME message.
    I am getting prob at following line.
      //soc is the object of Socket
      Session session =Session.getDefaultInstance(new Properties(), null);
      MimeMessage l_msg = new MimeMessage(session, soc.getInputStream());When I read the input stream from the file.
    It works successfully. But when I try to get it from socket not doesn't work.
    It's not showing any error also. So I am not able to track the actual error.
    Could you please tell me why it is not working.
    Thanks
    Anmolb

  • Send a image through socket method getoutputstream

    cani send an image through socket methods instead of send a txt

    1) Use the search feature, or look back a couple of pages, this question was asked sometime yesterday
    2) In all the many times that it's been asked, no-one denies it but at the same time no-one's posted any code to do it (AFAIK) I'd be interested too if anyone does find a way...

  • Send Object through Socket

    Hi,
    I am trying to send an object from Server to Client but the ObjectInputStream.readObject() on the client blocks.
    net beans Project can be found Here .
    Why it doesn't work?
    Thanks,
    Itay

    The Server works fine... it waits for a second client after the first one get connected
    I will post here the code.
    Server Code
    public class MemoryServer
        private final static int DEFAULT_BOARD_SIZE = 4;
        private ServerSocket socket;
         * Starting the server
         * @param n integer to determine the size of the board (must be even) the board will be n*n.
         * @param port the port on which the server will listen for incoming requests
        public void startServer(int n, int port)
            try
                socket = new ServerSocket(port);
            catch (IOException e)
                e.printStackTrace();
                System.exit(1);
            while(true)
                System.out.println("Listening on port " + port);
                Socket firstPlayerSocket = null, secondPlayerSocket = null;
                try
                    firstPlayerSocket = socket.accept();
                    System.out.println("First Player Socket Open: " + firstPlayerSocket.getInetAddress() + ":" + firstPlayerSocket.getPort());
                    MemoryGame game = new MemoryGame(n, firstPlayerSocket);
                    secondPlayerSocket = socket.accept();
                    System.out.println("Second Player Socket Open: " + secondPlayerSocket.getInetAddress() + ":" + secondPlayerSocket.getPort());
                    game.setSecondPlayer(secondPlayerSocket);
                    game.start();
                catch (IOException e1)
                    try
                        e1.printStackTrace();
                        if (firstPlayerSocket != null)
                            firstPlayerSocket.close();
                        if (secondPlayerSocket != null)
                            secondPlayerSocket.close();
                    catch (IOException e2)
                        e2.printStackTrace();
    public class MemoryGame extends Thread
        private Socket firstPlayerSocket, secondPlayerSocket;
        private ObjectOutputStream firstPlayerOut, secondPlayerOut;
        private ObjectInputStream firstPlayerIn, secondPlayerIn;
        private int boardSize;
        public MemoryGame(int boardSize, Socket firstPlayer) throws IOException
            this.boardSize = boardSize;
            firstPlayerSocket = firstPlayer;
            firstPlayerOut = new ObjectOutputStream(firstPlayerSocket.getOutputStream());
            firstPlayerOut.flush();
            firstPlayerIn = new ObjectInputStream(firstPlayerSocket.getInputStream());
            TextMessage message = new TextMessage("Waiting for opponent.");  //TextMesaage extends Message which implements Serializable
            firstPlayerOut.writeObject(message);
            firstPlayerOut.flush();
        public void setSecondPlayer(Socket secondPlayer) throws IOException
            try
                secondPlayerSocket = secondPlayer;
                secondPlayerOut = new ObjectOutputStream(secondPlayerSocket.getOutputStream());
                secondPlayerOut.flush();
                secondPlayerIn = new ObjectInputStream(secondPlayerSocket.getInputStream());
                TextMessage message = new TextMessage(Constants.GAME_START_MESSAGE);
                firstPlayerOut.writeObject(message);
                firstPlayerOut.writeObject(message);
            catch(IOException e)
                firstPlayerIn.close();
                firstPlayerOut.close();
                if (secondPlayerIn != null)
                    secondPlayerIn.close();
                if (secondPlayerOut != null)
                    secondPlayerOut.close();
                throw e;
        @Override
        public void start()
            endGame();
        private void endGame()
            try
                firstPlayerIn.close();
                firstPlayerOut.close();
                firstPlayerSocket.close();
                secondPlayerIn.close();
                secondPlayerOut.close();
                secondPlayerSocket.close();
            catch (IOException e)
                e.printStackTrace();
    }Client Code
    public class MemoryClient
        private Socket socket;
        public MemoryClient(String host, int port)
            try
                socket = new Socket(host, port);
                ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
                System.out.println("Connected to " + host + ":" + port);
                while (true)
                    try
                        Message msg = (Message)in.readObject();
                        System.out.println("Recieved");
                        if (msg instanceof TextMessage)
                            TextMessage textMsg = (TextMessage)msg;
                            if (!textMsg.getText().equals(Constants.GAME_START_MESSAGE))
                                System.out.println(textMsg.getText());
                                break;
                            MemoryFrame gameFrame = new MemoryFrame(socket);
                            gameFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    catch(Exception e)
                        e.printStackTrace();
            catch (IOException e)
                e.printStackTrace();
                System.exit(1);
    }

  • Send Java objects through a socket

    I want to send some java objects to a J2SE server from a J2me socket. In normal j2me socket there is no way of putting whole obejct to the output stream. Is there any way that you can send a object from a socket ? Please advice..
    Thanks.

    Check this article on making serializable objects in MIDP. If the objects you want to send receive across the network implement this, then you can easily transform them into byte arrays and back to objects so they can be sent across a network.
    shmoove

  • How to send string data through socket!

    Is there any method to send string data over socket.
    and if client send string data to server,
    How to get that data in server?
    Comments please!

    Thank for your kind answer, stoopidboi.
    I solved the ploblem. ^^;
    I open the source code ^^; wow~~~~~!
    It will useful to many people. I spend almost 3 days to solve this problem.
    The program works like this.
    Client side // string data ------------------------> Server side // saving file
    To
    < Server Side >
    * Server.java
    * Auther : [email protected]
    import java.io.*;
    import java.net.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Server extends JFrame
         private JTextField enter;
         private JTextArea display;
         ObjectInputStream input;
         DataOutputStream output;
         FileOutputStream resultFile;
         DataInputStream inputd;
         public Server(){
              super("Server");
              Container c = getContentPane();
              enter = new JTextField();
              enter.setEnabled(false);
              enter.addActionListener(
                   new ActionListener(){
                        public void actionPerformed(ActionEvent ev){
                             //None
              c.add(enter, BorderLayout.NORTH);
              display = new JTextArea();
              c.add(new JScrollPane(display),
                     BorderLayout.CENTER);
              setSize(300, 150);
              show();
         public void runServer(){
              ServerSocket server;
              Socket connection;
              int counter = 1;
              display.setText("");
              try{
                   server = new ServerSocket(8800, 100);
                   while(true){
                        display.append("Waiting for connection\n");
                        connection = server.accept();
                        display.append( counter + " connection is ok.\n");
                        display.append("Connection " + counter +
                             "received from: " + connection.getInetAddress().getHostName());
                        resultFile = new FileOutputStream("hi.txt");
                        output = new DataOutputStream(resultFile);
                        output.flush();
                        inputd = new DataInputStream(
                             connection.getInputStream()
                        display.append("\nGod I/O stream, I/O is opened\n");
                        enter.setEnabled(true);
                        try{
                             while(true){
                                  output.write(inputd.readByte());
                        catch(NullPointerException e){
                             display.append("Null pointer Exception");
                        catch(IOException e){
                             display.append("\nIOException Occured!");
                        if(resultFile != null){
                             resultFile.flush();
                             resultFile.close();
                        display.append("\nUser Terminate connection");
                        enter.setEnabled(false);
                        resultFile.close();
                        inputd.close();
                        output.close();
                        connection.close();
                        ++counter;
              catch(EOFException eof){
                   System.out.println("Client Terminate Connection");
              catch(IOException io){
                   io.printStackTrace();
              display.append("File is created!");
         public static void main(String[] args){
              Server app = new Server();
              app.addWindowListener(
                   new WindowAdapter(){
                        public void windowClosing(WindowEvent e){
                             System.exit(0);
              app.runServer();
    < Client side >
    * Client.java
    * Auther : [email protected]
    package Client;
    import java.io.*;
    import java.net.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Client extends JFrame
         private JTextField enter;
         private JTextArea display;
         DataOutputStream output;
         String message = "";
         public Client(){
              super("Client");
              Container c = getContentPane();
              enter = new JTextField();
              enter.setEnabled(false);
              enter.addActionListener(
                   new ActionListener(){
                        public void actionPerformed(ActionEvent e){
                             //None
              c.add(enter, BorderLayout.NORTH);
              display = new JTextArea();
              c.add(new JScrollPane(display), BorderLayout.CENTER);
              message = message + "TT0102LO12312OB23423PO2323123423423423423" +
                        "MO234234LS2423346234LM2342341234ME23423423RQ12313123213" +
                        "SR234234234234IU234234234234OR12312312WQ123123123XD1231232" +
                   "Addednewlinehere\nwowowowwoww";
              setSize(300, 150);
              show();
         public void runClient(){
              Socket client;
              try{
                   display.setText("Attemption Connection...\n");
                   client = new Socket(InetAddress.getByName("127.0.0.1"), 8800);
                   display.append("Connected to : = " +
                          client.getInetAddress().getHostName());
                   output = new DataOutputStream(
                        client.getOutputStream()
                   output.flush();
                   display.append("\nGot I/O Stream, Stream is opened!\n");
                   enter.setEnabled(true);
                   try{
                        output.writeBytes(message);
                   catch(IOException ev){
                        display.append("\nIOException occured!\n");
                   if(output != null) output.flush();
                   display.append("Closing connection.\n");
                   output.close();
                   client.close();
              catch(IOException ioe){
                   ioe.printStackTrace();
         public static void main(String[] args){
              Client app = new Client();
              app.addWindowListener(
                   new WindowAdapter(){
                        public void windowClosing(WindowEvent e){
                             System.exit(0);
              app.runClient();

  • Send encypted bytes through socket

    I am trying to send some encypted bytes to another socket, and I use the code below:
    byte[] encrypted = encrypt(myString);
    DataOutputStream ostream = new DataOutputStream(socket.getOutputStream());
    ostream.writeInt(encrypted.length);
    ostream.write(encrypted);
    To receive:
    DataInputStream istream = new DataInputStream(socket.getInputStream());
    byte[] encrypted = new byte[istream.readInt()];
    istream.read(encrypted);
    String decrypted = decrypt(encrypted);
    But the bytes I received was wrong, can somebody give me any idea about it?

    You should be using the
    write(byte[], int, int) method to write your byte array to the
    DataOutputStream (and the read(byte[]) or read(byte[], int, int) for reading).
    They are more efficient then using the writeByte type methods. And you
    may avoid some of the problems you are getting. If the problems persist
    ensure that your encryption and decryption are working properly.
    matfud

  • Send key sequence through socket.

    Hi!
    I have programmed an application which makes a socket-connection to a telnet-server. All this have went good. The problem I'm having is sending keysequences. Let's say that I want to perform a "Ctrl-c"... how do I do this?

    You may have to listen for keyPressed method calls (KeyListener), not just keyTyped, to watch for the control key being pressed. If you see the control key pressed, begin your translation into control characters or special key sequences. Then when keyReleased says the control key has been released, stop your translation.
    e.g. I believe the CTRL plus the keypad Minus key do not send an intelligent keyPressed event. So you'll have to watch for the combination yourself, then send the codes you want to represent that down the stream.

  • Logging through sockets

    Hi
    I'm trying to send logging information through sockets using log4j.
    My configuration file is :
    log4j.rootLogger=Debug, Socket
    log4j.appender.Socket=org.apache.log4j.net.SocketAppender
    log4j.appender.Socket.Port=12345
    log4j.appender.Socket.RemoteHost=localhost
    log4j.appender.Socket.LocationInfo=true
    the server only reads the input string that the logger sends.
    I'm getting this exception on the client side:
    log4j:WARN Detected problem with connection: java.net.SocketException: Software caused connection abort: socket write error
    and this message on the server:
    Server started...
    Client accepted
    ������������org.apache.log4j.spi.LoggingEven�������������

    Ryan,
    I think if I could log to something common like Microsoft Access it would be a help to me in managing database backups and other things, as Citadel is somewhat unique in its format and methods using the Measurement and Automation Explorer. Maybe I could retrieve data from a 3rd party database back into Citadel if Citadel DB becomes corrupted or lost.
    I don't use ODBC logging now, so please excuse me if I come across as lacking in understanding your request. Could the hypertrend or other objects be programmed to log and/or retrieve data to and/or from the 3rd party ODBC database as well?
    Terry Parks, Engineering Analyst
    Terrebonne Parish Consolidated Government (T.P.C.G.)
    Public Works - Pollution Control

  • How to send data to bam data object through java code

    how to send data to bam data object through java code

    I've made a suggestion in other thread: https://forums.oracle.com/thread/2560276
    You can invoke BAM Webservices (Using Oracle BAM Web Services) or use JMS integration using Enterprise Message Sources (http://docs.oracle.com/cd/E17904_01/integration.1111/e10224/bam_ent_msg_sources.htm)
    Regards
    Luis Fernando Heckler

  • Sockets: can only send once file through

    Hi,
    I am using sockets to send text and files to a client on a Clio. I want to send multiple files through. However, only the first file goes through. The rest are never received (although they are uploaded). My question is:
    Why can not send anything through the socket (text or files) after the first file is sent?
    The fileSend() is on the server side, fileReceive is on the client side.
    public static void fileSend (Socket uploadSocket, String source) {
         try {
             InputStream inFile = new FileInputStream(source);
             InputStream in = new BufferedInputStream(inFile);
             OutputStream out = new BufferedOutputStream(uploadSocket.getOutputStream());
             System.out.println("Sending " + source + ".");
             int data;
             int bytes = 0;
             while ((data = in.read()) != -1) {
              bytes++;
              out.write(data);
             bytes++;
             out.write(data);
             if (in != null) in.close();
             if (out != null) out.flush();
             System.out.println("Upload complete: " + bytes + " Bytes!");
         catch (Exception e) {
             System.err.println("Couldn't upload " + source + ": " + e.getMessage());
       public static void fileReceive (Socket downloadSocket, String destination) {
         try {
             InputStream in = new BufferedInputStream(downloadSocket.getInputStream());
             OutputStream outFile = new FileOutputStream(destination);
             OutputStream out = new BufferedOutputStream(outFile);
             System.out.println("Downloading data to " + destination + ".");
             int data = in.read();
             int bytes = 0;
             while (data != -1) {
              bytes++;
              out.write(data);
              data = in.read();
             bytes++;
             if (out != null) {
              out.flush();
              out.close();
             outFile.close();
             System.out.println("Download complete: " + bytes + " Bytes!");
             in.skip(in.available());
         catch (Exception e) {
             System.err.println("Couldn't download " + destination + ": " + e.getMessage());
        }Thanks,
    Neetin

    I think its better to pass the outputstream to the filesend() method and inputstream to fileReceive() method
    something like this:
    OutputStream out = new BufferedOutputStream(uploadSocket.getOutputStream());
    public static void fileSend (OutputStream os, String source) {
      //write your file onto the output stream
    InputStream in = new BufferedInputStream(downloadSocket.getInputStream());
    public static void fileReceive (InputStream is) {
      //Read from the input stream
    }This should work.. Good luck

  • Read contents of file into outputstream and send through socket

    I have a file. Instead of transferring the whole file through socket to the destination, I will read the contents from the file (big or small file size) into outputstream and send them to the destination where the client will receive the data and directly display it....
    Can you suggest any efficient way/methods to achieve that?
    Thanks.

    I don' t understand what you think the difference is between those two techniques, but:
    int count;
    byte[] buffer = new byte[16384];
    while ((count = in.read(buffer)) > 0)
      out.write(buffer, 0, count);
    out.close();
    in.close();

  • Sending objects over sockets - issues i am having

    Hi, this is my first time posting on these forums and I have exhausted my mental capacity on this problem i have been having the past few days. Hopefully somone could help me out.
    I am doing a uni project, and the goal i am currently trying to achieve is to send an object (serialized) from a client to a server. I will atach the code i have written and i will explain more from there.
    This is the server (part of the class, which calls this method)
    Constructor:
      public Broker(String bID) throws Exception {
        brokerID = bID;
        bServer = new ServerSocket(Integer.parseInt(bID));
        System.out.println("Broker listening on port " + bID);
        this.start();
    Main method
      public static void main(String[] args) throws Exception {
        new Broker("8008");
    run method
      public void run() {
        while(true) {
          try {
            Socket bSocket = bServer.accept();
            System.out.println("Accepted a connection from: " + bSocket.getInetAddress());
            brokerServer(bSocket);
            bSocket.close();
            System.out.println("Connection closed");
          catch (Exception e) { e.printStackTrace(); }
    Broker Server
      public void brokerServer(Socket bSocket) {
        BufferedReader in = null;
        ObjectOutputStream oos = null;
        PrintWriter out = null;
        ObjectInputStream ois = null;
        try {
          while (true) {
            oos = new ObjectOutputStream(new DataOutputStream(bSocket.getOutputStream()));
            out = new PrintWriter(new OutputStreamWriter(bSocket.getOutputStream()));
            ois = new ObjectInputStream(bSocket.getInputStream());
            in = new BufferedReader(new InputStreamReader(bSocket.getInputStream()));
            out.println("Connection with Broker on port " + brokerID + " established");
            out.flush();
            //read in first line
            String str = in.readLine();
            //if lineis null, break while loop
            if (str == null)  break;
            else {
              //a request is recieved from user to get user certificate
              if (str.trim().equals("GETUSERCERT")) {
                //read in the userName, size of paywords and user publick key (used in certificate)
                String userName = in.readLine();
                String size = in.readLine();
                PublicKey userPk = (PublicKey) ois.readObject();
                //generate user certificate
                UserCertificate uc = generateUserCertificate(userName, userPk, Integer.parseInt(size, 10));
                //send text to user stating next message is user certififcate
                out.println("SENDUSERCERT");
                out.flush();
                //user Certificate
                oos.writeObject( (UserCertificate) uc);
                oos.flush();
                break;
              if (str.trim().equals("FINISH"))
                break;
            ois.close();
            oos.close();
            out.close();
            in.close();
        catch(Exception e) { e.printStackTrace(); }
    This is the client
      private void requestUserCertificate(int sizeOfPaywordChain, String BrokerID) {
        String host = "localhost";
        ObjectOutputStream oos = null;
        ObjectInputStream ois = null;
        PrintWriter out = null;
        BufferedReader in = null;
        Socket u2bSocket = null;
        try {
          u2bSocket = new Socket(host, Integer.parseInt(BrokerID));
          System.out.println("Connecting to Broker on port " + BrokerID);
          ois = new ObjectInputStream(new DataInputStream(u2bSocket.getInputStream()));
          oos = new ObjectOutputStream(u2bSocket.getOutputStream());
          out = new PrintWriter(new OutputStreamWriter(u2bSocket.getOutputStream()));
          in = new BufferedReader(new InputStreamReader(u2bSocket.getInputStream()));
          //Informs broker that a user certificate is being requested
          out.println("GETUSERCERT");
          //send to broker, username and size of payword chain
          out.println(userName);
          out.println(sizeOfPaywordChain);
          out.flush();
          //send user's public key accross
          oos.writeObject((PublicKey) userPublicKey);
          oos.flush();
          out.println("FINISH");
          out.flush();
          //wait for response
          while(true) {
            //read in line
            String str = in.readLine();
            //if line is null, break while loop
            if (str == null) break;
            //if line read is "SENDUSERCERT" then next line is userCertificate sent from Broker
            if (str.trim().equals("SENDUSERCERT")) {
              //read User Certificate
              userCert = (UserCertificate)ois.readObject();
              break;
            else System.out.println(str);
          //close connections and streams
          u2bSocket.close();
          ois.close();
          oos.close();
          out.close();
          in.close();
        catch (Exception e) { e.printStackTrace(); }
      }I will be regurarly checking this thread, so any other code which you think i should post i will, i can post is ASAP.
    The problem
    First time i run the programs, it works perfectly, however when i run the client program again, it shows this error
    java.io.EOFException
         at java.io.ObjectInputStream$BlockDataInputStream.peekByte(ObjectInputStream.java:2438)
         at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1245)
         at java.io.ObjectInputStream.readObject(ObjectInputStream.java:324)
         at User.requestUserCertificate(User.java:75)
         at User.main(User.java:278)the broker server doesn't display anything.
    Would anyone have any idea whats going on??
    Sometimes when i run it, it might display the above error, or it might work. its about 50/50. I have read heaps of similar problems people have had and posted on this forum, but i still don't have any luck in solving this delema.
    Any kind of help will be greatly appreciated.
    Rish

    I see one problem with the code. You are opening both ObjectInputStream ois and a BufferedReader in on the same socket. This won't work as "in" will read ahead to fill up its buffer. This could cause "ois" to find the socket already at end of stream prematurely. I would only use the Object Streams and send the strings as objects.

  • Send many files through a socket without closing Buffered Streams?

    Hi,
    I have an application that sends/receives files through a socket. To do this, on the receiver side I have a BufferedInputStream from the socket, and a BufferedOutputStream to the file on disk.
    On the sender side I have the same thing in reverse.
    As you know I can't close any stream, ever.. because that closes the underlying socket (this seems stupid..?)
    therefore, how can I tell the receiver that it has reached the end of a file?
    Can you show me any examples that send/receive more than one file without closing any streams/sockets?

    Hi,
    As you know I can't close any stream, ever.. because that closes the underlying socket (this seems stupid..?)Its not if you want to continuosly listen to the particular port.. like those of server, you need to use ServerSocket.
    for sending multiple files the sender(Socket) can request the file to server (ServerSocket). read the contents(file name) and then return the file over same connection, then close the connection.
    For next file you need to request again, put it in loop that will be better.
    A quick Google gives me this.
    Regards,
    Santosh.

Maybe you are looking for

  • Search help for material code in VA01

    Dear Experts, In VA01 tcode in item level if user press f4 in the material code then we will get all the f4 helps for few fields.Now i need to add one more field  mtart from mara table  in the existing  search help of material code. plz suggest me ho

  • How do i get to the top of an iTunes playlist without having to scroll all the way

    when i am down at the bottom of one of my playlists and i want to get to the top i have to scroll through thousands of songs and it takes forever i was just wondering if there is an easier way to get to the top of a playlist?

  • Internal Order settlement

    Hi All, When am trying to settle one internal order to an asset, System is selecting the amount from all the cost elements which have carried the cost. But if i want to settle only from one cost element how should i do that. Ex: Order 700002 Cost ele

  • How to read data from PC format external disk, using Labview MAC

    Hi folks, For years I have not been able to read data files from a PC formatted (created) external disk, using Labview for Mac. More specifically:  - I have Labview 7.01 running on OS X 10.4.11 on a PowerBook G4  - I have a 500GB external USB/firewir

  • Language Conversion problem.

    I follow the tutorial for converting english(us) to germany (de) ...no problem when i try to convert english (us) to chinese (zh)....it doesnt convert any idea ...