Receiving a HashMap over a socket

Hi,
in my client/server program, my server is sending a HashMap like this:
public HashMap myMap = new HashMap();
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
out.println(myMap);On the receiver side, how do I receive this? I have this code:
public HashMap myReceivedMap = new HashMap();
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
myReceivedMap = (HashMap)in.readLine();But, alas, I get the inconvertible types problem, where the compiler is telling me that in.readLine() will return a String, not a HashMap. So, how do I get around this? Like, HashMap constructors don't take Strings....
Thanks,
Jeff

When you execute this line
out.println(myMap);
what is being written is not the object itself, but whatever its toString() method returns (probably meaningless to you)
Try using ObjectOutputStream & ObjectInputStream

Similar Messages

  • Audio over TCP Socket

    Hi,
    I need a sample code for transmit/receive a audio over TCP socket.. can anybody help me?

    You send and receive it in the same way as you handle any binary data.
    Kaj

  • Streaming sound over a socket

    Does anyone know how to capture sound on a microphone and streamed over a socket connection to a remote machine. When the remote machine receives this it plays it directly to speakers.
    I don't want to capture a bit of sound and send a sound file I would like to be able to stream it like an internet phone.
    Does anyone know what would be the best way to go about doing this?

    http://search.java.sun.com/search/java/index.jsp?col=javaforums&qp=&qt=%2Bvoice+%2Bover&x=13&y=2
    http://www.google.com/search?hl=en&lr=&ie=UTF-8&oe=UTF-8&q=%2Bvoice+%2Bover++%2Binternet

  • Detect "end of file" while send n numbers files over a socket?

    Hi!
    I�m trying to find a way to detect "end of file" while send n numbers files over a socket.
    What i'm looking for is how to detect on the client side when the file i�m sending is downloaded.
    Here is the example i�m working on.
    Client side.
    import java.io.*;
    import java.net.*;
    public class fileTransfer {
        private InputStream fromServer;
        public fileTransfer(String fileName) throws FileNotFoundException, IOException {
            Socket socket = new Socket("localhost", 2006);
            fromServer = socket.getInputStream();
            for(int i=0; i<10; i++)
                receive(new File(i+fileName));
        private void receive(File uploadedFile) throws FileNotFoundException, IOException {
            uploadedFile.createNewFile();
            FileOutputStream toFile = new FileOutputStream(uploadedFile);
            byte[] buffer = new byte[4096];
            int bytesRead = 0;
            while ((bytesRead = fromServer.read(buffer)) != -1) {
                toFile.write(buffer, 0, bytesRead);
        public static void main(String[] args) {
            try {
                new fileTransfer("testa.jpg");
            } catch (Exception ex) {ex.printStackTrace();}
    }Server side.
    import java.io.*;
    import java.net.*;
    public class fileTransferSend {
        Socket serv = null;
        OutputStream toClient;
        public fileTransferSend(String fileName) throws FileNotFoundException, IOException {
            StartServer();       
            for(int i =0; i<10; i++)
                send(new File(fileName));
        public void StartServer() throws IOException {
            ServerSocket ssocket = new ServerSocket(2006);
            System.out.println("Waiting for incomming");
            serv = ssocket.accept();
            System.out.println("incomming");
            toClient = serv.getOutputStream();
        private void send(File f) throws FileNotFoundException, IOException {
            if(f.exists() && f.canRead()) {
                FileInputStream fromFile = new FileInputStream(f);
                try {
                    byte[] buffer = new byte[4096]; // 4K
                    int bytesRead = 0;
                    System.out.println("sending: "+f.getName());
                    while ((bytesRead = fromFile.read(buffer)) != -1) {
                        toClient.flush();
                        toClient.write(buffer, 0, bytesRead);
                finally {
                    //toClient.close();
                    fromFile.close();
            } else {
                System.out.println("no files");
        public static void main(String[] args) {
            try {
                new fileTransferSend("test.jpg");
            }catch(Exception e) {e.printStackTrace();}
    I know that the client never reads -1 becuase i doesn�t close the stream.
    Is there anyway to tell the client that the file is downloaded?

    A common (and easy) TCP/IP protocol is to send length, followed by data.
    Because TCP/IP is a stream-oriented protocol, a receiver can never absolutely determine where the first packet ends and the second packet begins. So it is common to send the length of the packet, followed by the packet itself.
    In your case, you could send length of file, followed by file data. It should be fairly easy to obtain file length and send that as a 32-bit (or 64-bit value). Here is an idea (not code) for the receiver:
    receive (4) // where 4 = number bytes to receive
    unsigned length = convert 4 bytes to unsigned integer
    while (length != 0)
    n = receive ( length ) // where n = number bytes actually received, and length = number bytes desired
    Or, you can use the concept of an "Escape" character in the stream. Arbitrarily choose an ESCAPE character of 0x1B (although it could be any 8-bit value). When the receiver detects an ESCAPE char, the next character can be either control or data. So for end of file you might send 0x1B 0x00. If the byte to be sent is 0x1B, then send 0x1B 0x1B. The receiver would look something like this:
    b = read one byte from stream
    if (b == 0x1B)
    b = read one byte from stream
    if (b == 0x00) then end of file
    else place b in buffer
    else
    place b in buffer
    Later.

  • Write updated Object with ObjectOutput Stream over a socket

    Hello,
    i would like to use an ObjectOutput Stream ot write over a socket between 2 process. But each time the object is modified on a given process i would like to resend it to the other in order to get the object updated.
    My porblem is that the object is never retrieved in its modified state on the second process.
    here is the class that i'm using to send and receive objects.
    On the server it is instanciated with serverMode=true and false on the client
    public class GameClient extends Thread
         private String m_servername="";
         private int m_serverport=0;
         private ObjectOutputStream m_oos = null;
         private ObjectInputStream m_ois = null;
         private Socket m_socket = null;
         private ServerSocket m_serverSocket = null;
         private Vector<INetworkController> m_listeners = new Vector<INetworkController>();
         private static final Trace trace = new Trace("SimpleClient");
         private boolean m_serverMode=false;
         public GameClient(String serverName,int port,boolean serverMode) throws IOException, UnknownHostException
              try
                   m_serverMode = serverMode;
                   m_servername=serverName.trim();
                   m_serverport=port;
                   if (m_serverMode)
                        m_serverSocket = new ServerSocket( m_serverport);
                   else
                        m_socket = new Socket(m_servername, m_serverport);
                        m_oos = new ObjectOutputStream(m_socket.getOutputStream());
                        m_ois = new ObjectInputStream(m_socket.getInputStream());
                   start();
              catch (BindException e)
                   e.printStackTrace();
                   String message = "Impossible de lancer le serveur. Un autre process �coute d�j� sur ce port";
                   System.exit(0);
         public void run()
              try
                   if (m_serverMode)
                        Socket client = m_serverSocket.accept();
                        m_oos = new ObjectOutputStream(client.getOutputStream());
                        m_ois = new ObjectInputStream(client.getInputStream());
              catch(Exception e)
                   e.printStackTrace();
              trace.startMethod("run()");
              trace.println("Listening Client Thred started");
              while(true)
                   try
                        Event serverMessage = (Event) m_ois.readObject();
                        trace.println("Waiting for message");
                        dispatchEvent(serverMessage);
                        trace.println("Message Reveived");
                   catch(Exception e)
                        String message = "La connexion r�seau a �t� perdue";
                        e.printStackTrace();
                        trace.endMethod();
                        try
                             if(m_socket!=null)
                                  m_socket.close();
                             if (m_serverSocket!=null)
                                  m_serverSocket.close();
                             m_oos.close();
                             m_ois.close();
                        catch (Exception e2)
                             e2.printStackTrace();
                        return;
         private int m_counter=0;
         public void sendNetworkMessage(Event msg)throws IOException, UnknownHostException
              if (m_oos != null)
                   m_oos.writeObject(msg);     
                   m_oos.flush();
                   //m_oos.reset();
              time = System.currentTimeMillis()-time;
              trace.endMethod();
         }Each time an object can be read, the read object is dispatch with the method dsiaptchEvent() which is not described here...
    I do not inderstand what's wrong in here
    Edited by: Voldor on Oct 16, 2007 4:10 PM

    Thanks but if i uncomment m_oos.reset() each time i write something on the socket (on the client or on the server) it is more and more longer to retrieve the writeen object on the other side of the socket (more than 40 sec after 12 messages exchanged, 6 coming from the server and 6 form the client)
    and after all i got the following
    java.lang.ArrayIndexOutOfBoundsException
         at java.net.SocketInputStream.socketRead0(Native Method)
         at java.net.SocketInputStream.read(Unknown Source)
         at java.net.SocketInputStream.read(Unknown Source)
         at java.io.ObjectInputStream$PeekInputStream.peek(Unknown Source)
         at java.io.ObjectInputStream$BlockDataInputStream.peek(Unknown Source)
         at java.io.ObjectInputStream$BlockDataInputStream.peekByte(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.readArray(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.defaultReadFields(Unknown Source)
         at java.io.ObjectInputStream.readSerialData(Unknown Source)
         at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.defaultReadFields(Unknown Source)
         at java.io.ObjectInputStream.readSerialData(Unknown Source)
         at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.readArray(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.defaultReadFields(Unknown Source)
         at java.io.ObjectInputStream.readSerialData(Unknown Source)
         at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.defaultReadFields(Unknown Source)
         at java.io.ObjectInputStream.readSerialData(Unknown Source)
         at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.defaultReadFields(Unknown Source)
         at java.io.ObjectInputStream.readSerialData(Unknown Source)
         at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.readArray(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.defaultReadFields(Unknown Source)
         at java.io.ObjectInputStream.readSerialData(Unknown Source)
         at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.defaultReadFields(Unknown Source)
         at java.io.ObjectInputStream.readSerialData(Unknown Source)
         at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.readArray(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.defaultReadFields(Unknown Source)
         at java.io.ObjectInputStream.readSerialData(Unknown Source)
         at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.defaultReadFields(Unknown Source)
         at java.io.ObjectInputStream.readSerialData(Unknown Source)
         at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.defaultReadFields(Unknown Source)
         at java.io.ObjectInputStream.readSerialData(Unknown Source)
         at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.defaultReadFields(Unknown Source)
         at java.io.ObjectInputStream.readSerialData(Unknown Source)
         at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.readArray(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.defaultReadFields(Unknown Source)
         at java.io.ObjectInputStream.readSerialData(Unknown Source)
         at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.defaultReadFields(Unknown Source)
         at java.io.ObjectInputStream.readSerialData(Unknown Source)
         at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.defaultReadFields(Unknown Source)
         at java.io.ObjectInputStream.readSerialData(Unknown Source)
         at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.readArray(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.defaultReadFields(Unknown Source)
         at java.io.ObjectInputStream.readSerialData(Unknown Source)
         at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.defaultReadFields(Unknown Source)
         at java.io.ObjectInputStream.readSerialData(Unknown Source)
         at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.readArray(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.defaultReadFields(Unknown Source)
         at java.io.ObjectInputStream.readSerialData(Unknown Source)
         at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.defaultReadFields(Unknown Source)
         at java.io.ObjectInputStream.readSerialData(Unknown Source)
         at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.defaultReadFields(Unknown Source)
         at java.io.ObjectInputStream.readSerialData(Unknown Source)
         at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.defaultReadFields(Unknown Source)
         at java.io.ObjectInputStream.readSerialData(Unknown Source)
         at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.readArray(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.defaultReadFields(Unknown Source)
         at java.io.ObjectInputStream.readSerialData(Unknown Source)
         at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.defaultReadFields(Unknown Source)
         at java.io.ObjectInputStream.readSerialData(Unknown Source)
         at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.defaultReadFields(Unknown Source)
         at java.io.ObjectInputStream.readSerialData(Unknown Source)
         at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.readArray(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.defaultReadFields(Unknown Source)
         at java.io.ObjectInputStream.readSerialData(Unknown Source)
         at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.defaultReadFields(Unknown Source)
         at java.io.ObjectInputStream.readSerialData(Unknown Source)
         at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.readArray(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.readArray(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.defaultReadFields(Unknown Source)
         at java.io.ObjectInputStream.readSerialData(Unknown Source)
         at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.readArray(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.defaultReadFields(Unknown Source)
         at java.io.ObjectInputStream.readSerialData(Unknown Source)
         at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.defaultReadFields(Unknown Source)
         at java.io.ObjectInputStream.readSerialData(Unknown Source)
         at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.defaultReadFields(Unknown Source)
         at java.io.ObjectInputStream.readSerialData(Unknown Source)
         at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.defaultReadFields(Unknown Source)
         at java.io.ObjectInputStream.readSerialData(Unknown Source)
         at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.defaultReadFields(Unknown Source)
         at java.io.ObjectInputStream.readSerialData(Unknown Source)
         at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.readObject(Unknown Source)
         at dt.communication.GameClient.run(GameClient.java:78)Do you have any idea ? Any recommandation about when to call reset ?
    Edited by: Voldor on Oct 16, 2007 4:44 PM

  • Emails received ok for over a year since buying ipad 2.Has not updated now for a month but had not changed any settings

    Why has my ipad 2 stopped receiving emails for over a month when I have not changed any settings

    Does the iPod connect to other networks?
    Does the iPod see the network?
    Any error messages?
    Try:
    - Reset the iOS device. Nothing will be lost
    Reset iOS device: Hold down the On/Off button and the Home button at the same time for at
    least ten seconds, until the Apple logo appears.
    - Power off and then back on the router
    - Reset network settings: Settings>General>Reset>Reset Network Settings
    - iOS: Troubleshooting Wi-Fi networks and connections
    - iOS: Recommended settings for Wi-Fi routers and access points
    - Restore from backup. See:
    iOS: How to back up
    - Restore to factory settings/new iOS device.
    - Make an appointment at the Genius Bar of an Apple store.
    Apple Retail Store - Genius Bar
    maybe this:
    iOS: Wi-Fi or Bluetooth settings grayed out or dim
    If not successful, an appointment at the Genius Bar of an Apple store is usually in order.
    Apple Retail Store - Genius Bar

  • Unable to receive internet connection over wifi connection.  Shows that I am connected to the network, but do not have internet access.  Checked my firewall and turned it off.  What else am I missing or should be doing differently?

    Unable to receive internet connection over wifi connection.  Shows that I am connected to the network, but do not have internet access.  Checked my firewall and turned it off.  What else am I missing or should be doing differently?

    You might want to try resetting your router and your modem - just unplug the cords, leave them unplugged for about 3-5 minutes and then replug the modem and then the router in that order.
    This may or may not correct your problem - call back if it doesn't.
    Clinton

  • Parse streaming XML over a socket

    Is it possible to parse XML incrementally over a socket connection? I would like to parse and respond dyanamically to streaming XML and I am looking for some direction. Everything that I have read so far with respect to parsing XML from files. Thanks in advance

    You will want to look into a SAX parser, they are specifically intended for parsing xml over an input stream. They call callbacks to handle each element that arrives from the socket.
    However, there are a lot of posts about the sax parsers hanging, and I just posted last week trying to find the cause/solution. I've seen a number of solutions posted, but none have worked in my case. No replies to my post yet.
    Steve

  • Hod do I pass a socket variable over a socket connection

    Anyone know what syntax I could use to pass a socket variable over a socket connection? I can't imagine it'll go as a string, int, or double. --That's all I know how to pass.                                                                                                                                                                                                                                                                                                                                                               

    I was trying to get two programs accesing a server
    program through the same socket connection. Are you
    telling me this is impossible? If so, please go to
    this link and give me a hand with the other way I
    think I can get this to work...Sure ya can....
    ...something like this:
    Server:
    ServerSocket serverSock = new ServerSocket(8888); // 8888 = whatever port you want to listen on
    while (bWaitingConnections)
      Socket socket = serverSock.accept(); // WAIT until client connects to our port.
      Thread thread = new MySocketHandlingThread(socket);
      thread.start();
    }Client:
    Socket socket = new Socket(sServerHostName, 8888);
    // ... connected to Server on port 8888 ....

  • Sending images over network socket

    I'm working on a java web server. So far i have managed to get it to send html documents sucessfully to the client web browser, using a BufferedReader, and a PrintWriter object.
    But how should i send images over the socket? using this method doesn't work. Any suggestions?
    Thanks in advance.
    hornetau

    I did it first. You may pay me $10 and get XM2 WebServer 1.2 from my company.
    Ok, I'll help ya out here...
    HTTP protocol in Internet Explorer is "juiced up" meaning that it does not require HTTP data to be correctly sent. To send an image to be deisplayed...
    <html>
    <img src="theImage.gif"></img>
    </html>
    Now, the server will see a GET request like this...
    GET /theImage.gif HTTP/1.1
    Accepts: Image/jpeg, Image/gif, ...
    Your web server (in the IE case just needs to send)...
    output.println(data);
    The data object is a string, that represents the contents of the image.
    To do that, just get the correct File object, connect reader to it, then loop it
    until the reader is no longer ready (reader.ready() != true), as it loops, just append
    the readLine() command to the end of the data string and it will be ok.
    Now this works on IE just fine, using vary small file sizes due to it being loaded directly into
    memory. Casing problem if your app has only 500K of memory and the file size is 700K, 500-700=-200K, so use only small file sizes with this method.
    There is also the URLConnection and HttpURLConnection classes to use that will do this better, but
    they dont have any real way of getting the file's data - that's still YOUR job.

  • I've recently received 3 emails over the last 2 weeks from admin@appleid-apple.co.uk asking me to confirm my apple id- I presume this is fake

    I have recently received 3 emails over the last 2 weeks from [email protected] I presume these are fake. Can anyone confirm

    https://appleid.apple.com
    Go to the above website, sign in to your AppleID using the "Manage your Apple ID" link, and make sure everything is correct.  If it is, then clearly, at the least, the emails are in error.

  • How do I send an Image over a socket ?

    I'm trying to get the output from my webcam and send that data out to a socket. Now the output from the webcam is running I'm just not sure how to send it out over the socket.
    Server.java
    import java.io.*;
    import java.net.*;
    public class Server {
       public static void main(String args[]) {
         ServerSocket serverSocket = null;
         boolean listening = true;
         try {
         serverSocket = new ServerSocket(1354);
         System.out.println("Listening for Connections...");
         } catch (IOException drr) {
         System.out.println("Error Listening :" + drr);
         System.exit(-1);
         try {
         while(listening)
         new ServerThread(serverSocket.accept()).start();
         } catch (IOException er) {
         System.out.println("Error Creating connection:" + er);
         try {
           serverSocket.close();
         } catch (IOException err) {
         System.out.println("Error Closing:" + err);
    }When a connection is made it will start the webcam and send the image.
    ServerThread.java
    import java.net.*;
    import java.io.*;
    import java.awt.*;
    import java.awt.image.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.io.*;
    import javax.media.*;
    import javax.media.format.*;
    import javax.media.util.*;
    import javax.media.control.*;
    import javax.media.protocol.*;
    import java.util.*;
    import java.awt.*;
    import java.awt.image.*;
    import java.awt.event.*;
    import com.sun.image.codec.jpeg.*;
    public class ServerThread extends Thread {
        public static Player player = null;
        public CaptureDeviceInfo di = null;
        public MediaLocator ml = null;
        public JButton capture = null;
        public Buffer buf = null;
        public Image img = null;
        public VideoFormat vf = null;
        public BufferToImage btoi = null;
        public ImagePanel imgpanel = null;
        private Socket socket = null;
        Image blah;
        PrintWriter out = null;
        public ServerThread(Socket socket) {
         super("ServerThread");
         this.socket = socket;
        public void run() {
         try {
             out = new PrintWriter(socket.getOutputStream(), true);        
             imgpanel = new ImagePanel();
                 String str1 = "vfw:CompUSA PC Camera:0";
                 String str2 = "vfw:Microsoft WDM Image Capture (Win32):0";
                 di = CaptureDeviceManager.getDevice(str2);
             ml = new MediaLocator("vfw://0");
                try {
               player = Manager.createRealizedPlayer(ml);
                 } catch (Exception npe) {
               System.out.println("Player Exception:" + npe);
                player.start();
             Component comp;
             if ((comp = player.getVisualComponent()) != null) {
               // Grab a frame
               FrameGrabbingControl fgc = (FrameGrabbingControl) player.getControl("javax.media.control.FrameGrabbingControl");
               buf = fgc.grabFrame();
               btoi = new BufferToImage((VideoFormat) buf.getFormat());
               //Send the image over the socket
               out.println(btoi);
         } catch (IOException e) {
             System.out.println("It bombed:" + e);
        public static void playerclose() {
           player.close();
           player.deallocate();
      class ImagePanel extends Panel {
        public Image myimg = null;
        public ImagePanel() {
        public void setImage(Image img) {
          this.myimg = img;
          repaint();
        public void paint(Graphics g) {
          if (myimg != null) {
            g.drawImage(myimg, 0, 0, this);
      }The output I get from running the server is this:
    BufferedImage@c9131c: type = 1 DirectColorModel: rmask=ff0000 gmask=ff00 bmask=ff amask=0 IntegerInterleavedRaster: width = 320 height = 240 #Bands = 3 xOff = 0 yOff = 0 dataOffset[0] 0
    Now how can I turn this into an image If this output is correct?

    HUH?
    I got the one to send the images over the network. I'm now trying to get the exact feed of the webcam and sending that over the network. This is alot more difficult to accomplish but I did see where I messed up my process of sending the images was just having to save the file then open it up put it in a byte array then send that over the network to the client. Once it was at the client i was able to re-construct it and throw it up in the frame. The only problem was lag. So this tells me it would be much more faster if instead of saving the file to send the client and having to reconstruct the image I should just send the webcam feed i used to make the image.
    eh, I guess I didn't need any help.
    Hey no offense or anything but you really have to learn how to spell better.

  • Passing info over a socket

    lets say I read in a vector from a file on a server, and I want to read the vector into another vector on the client side. I know the clients objectinputstream is the servers objectoutputstream, but how to I send objects over a socket connection.
    Thanks.

    client:
    public class Client implements Serializable
    Socket socket;
    // PrintWriter out;
    Vector userPass, guestBooks;
    BufferedReader inp;
    public Client()
    try
    socket = new Socket("13", 60);
    // out = new PrintWriter(socket.getOutputStream(), true);
            ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
            Object o1 = in.read();
            Object o2 = in.read();
            in.close();
    catch(IOException e)
    e.printStackTrace();
    Server:
    public class Server implements Serializable
    ServerSocket sock;
    Socket clnt;
    File file1, file2, file3;
    FileInputStream fis1, fis2, fis3;
    Vector userspass, guestbooks;
    public Server()
    try
    sock = new ServerSocket(60);
    System.out.println("Listening on: Port 60");
    clnt = sock.accept();
    file1 = new File("user.txt");
    file2 = new File("guestb.txt");
    fis1 = new FileInputStream(file1);
    fis2 = new FileInputStream(file2);
    ObjectInputStream in1 = new ObjectInputStream(fis1);
    ObjectInputStream in2 = new ObjectInputStream(fis2);
    userspass = new Vector();
    guestbooks = new Vector();
    try //read in the object from the file to the vectors
    while(in1.readObject()!= null)
    userspass.add(in1.readObject());
    while(in2.readObject()!= null)
    guestbooks.add(in2.readObject());
              // here you want to send the vectors to the client?
              ObjectOutputStream out = new ObjectOutputStream(clnt.getOutputStream());
              out.write(userspass);
              out.write(guestbooks);
              out.close();
    catch(Exception ex)
    ex.printStackTrace();
    sock.close();
    sock.close();
    catch(IOException e)
    e.printStackTrace();
    }Something like that. I have never used Object streams myself, so there's probably more to it (like making sure that vectors are serializable, and/or the contents in them). Also I'm not sure if closing the Object stream will close the socket's I/O stream also.... something for you to test and see.
    HTH,
    Radish21

  • Sending data over and socket

    when i send messages over socket and receive it using [line = in.readLine()/code]
    if there is a \r\n it stops and makes u have to use readLine again to get the rest of the message
    is there a way to send the message so it totally ignores the \r\n and i can just use readLine once to receive my complete string in one go
    as this newline thing is very annoying
    thanks :)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    I assume in is of type BufferedReader? If so, that is the definition of readLine.
    Other options:
    You can use java.util.Scanner to scan until the next delimiter, which you can set.
    You can use readUTF/writeUTF defined in interfaces DataInput/DataOut by
    using classes DataInputStream/DataOutputStream or ObjectInpuitStream/ObjectOutputStream.
    If you are using object stream, you could define any serializable objects you
    like for transmission.

  • How do I send an array over endpoint 2 and receive an array over endpoint 1?

    Background:
    I'm a device developer.  I have an HID device that interrupt transfers over endpoint 1 and endpoint 2.  The device enumerates successfully as an HID on mac, windows, and linux.  I've use a couple different .dll files to communicate with the device using visual studio and python with some success and now I'd like to get it to work in labview.
    Status to date:
    1.  Successfully installed device hijacker driver so NI MAX can see the device as USB::0x####::0x####:erialNumber::RAW (# inserted to protect the innocent and SerialNumber is an actual number)
    2.  I can see the device in MAX.  Tried to send a line of numbers and something is sent back, but it isn't useful yet.
    3.  Tried interruptusb.vi and it doesn't do anything but timeout.
    4.  Tried Read USB Descriptor Snippet1.vi and an 18 byte array shows up and the VID and PID are parsed out correctly if the bRequest is Get Descriptor and the Descriptor Type is Device.  None of the endpoint descriptor types return anything.  A bRequest won't trigger a device function.  It needs an array over the out endpoint.
    The problem:
    Intuitively I'm at a loss of what to do next.  The device needs to receive a command from a 16 byte array gets passed through the out endpoint (2).  Then it will respond with a 16 byte array through the IN endpoint(1).  It seems as though the interruptusb.vi should work, but the interrupt transfer is a receive only demonstration.  How should I format a 16 byte array to go through the out endpoint? Does it need to be flattened?  

    Thanks for the tip.
    The nuggets were great for getting started and helped with installing the labview hijack driver for the HID device.  Closer examination may lead to the conclusion that the code I'm using is very very similar to the nugget with minor changes to the output.  Definitely the nuggets are useful, but for my device, there is more to it. 
    It is not USBTMC compliant.  It requires an array of bytes be sent and received.  The problem may have to do with timing and ensuring that the byte transfer is correct.  When communicating from visual studio, a declared array of characters works fine.  I tried that with this setup and it doesn't work consistently.  Of particular concern is why with this setup the device shows up, doesn't work properly until stopped, then works fine, but when the labview VI is stopped, the device disappears and no longer available in the VISA combobox.  The Device Manager still shows the device, but Labview must have an open handle to it. 
    I'd really like to be able to call the dll used in Visual Studio, so the user can choose to use the included software or a Labview VI without having to reinstall a driver.  Afterall, HID is great because the driver is under the hood.  Having to load one for Labview defeats the purpose of developing an HID device.  If I wanted to load a driver, I'd program the device to be a USB-Serial device and use the labview VISA serial vi's. 
    For now I'll be happy to get a stable version in Labview that will communicate consistently even if it is the hijacked driver.

Maybe you are looking for

  • Error code; original file could not be found, would you like to locate it?

    when i try to transfer songs from my library to my ipod shuffle, i get this error message (error code; original file could not be found, would you like to locate it?). Then an exclamation point(!) in the first column it appears next to the song in th

  • Add lines to a PO with the PO API

    Hello All, Has anyone out there used the PO API to interface lines into an existing PO? Can this even be done? Thanks for any help, Bradley

  • Airradar reports WPA2(WEP) and I can find how to change this?

    While scanning my surroundings recently with airradar I noticed that it reports my 5GHz network as using the protocol WPA2 but the encryption type of WEP. I am using a dual band airport extreme that I purchased in January. I have looked on both the "

  • Attr change run in Process chain!

    Hi, For uploading Master data, we do have different process chains ( Eight to Nine ) for each client and for each source system! Now the requireement is such that there must be only two Two process chains one for daily uploads and another for weekly

  • Revenue Recognition Process in Oracle Projects

    I am new to Oracle Projects and needs to understand the Revenue Recognition process. User has created one Contract under which he has Intercompany Billing, Costing and Elimination Projects. He booked the cost under the Costing project and then ran a