1,080,578 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?

Posts by CPT

my FileWriter.cpp file consists of the following:

#include "FileWritter.h"

FileWritter::FileWritter(string fileName,const AbstractType& at)
{
    this->file.open(fileName.c_str());
    file<<(at);
}

FileWritter::~FileWritter(void)
{
    this->file.close();
}

I'm getting the following errors:

error C4430: missing type specifier - int assumed
error C2143: syntax error : missing ',' before '&'
error C2509: '{ctor}' : member function not declared in 'FileWritter'
error C2955: 'FileWritter' : use of class template requires template argument list
error C2509: '{dtor}' : member function not declared in 'FileWritter'

I'm using the class in the following way:

DefinedClass* DefinedClassPtr = new DefinedClass();
new FileWritter<DefinedClass>("fis.sg",*DefinedClassPtr);

I don't understand why I receive the errors

CPT
Light Poster
37 posts since Aug 2010
Reputation Points: 10
Solved Threads: 1
Skill Endorsements: 0

Currently I have something like this:

class FileWritter{
    ofstream file;
public:
    FileWritter(string filename,A_Class a){//A_Class is class which has defined the >> and the << operators
        file.open(filename.c_str());
        file<<a;
    }
    ~FileWritter(){
        file.close();
    }
};

what I want is to have something like this:

template <class AbstractClass>
class FileWritter{
    ofstream file;
    public:
    FileWritter(string fileName, AbstractClass ab){
        file.open(fileName.c_str());
        file<<ab;
    }
    ~FileWritter(){
        file.close();
    }
};

in this case, the compiller shows this error:

use of class template requires template argument list

my question is how can I use an template class with FileWritter?

CPT
Light Poster
37 posts since Aug 2010
Reputation Points: 10
Solved Threads: 1
Skill Endorsements: 0

Hello everyone, I'm having problems grasping some concepts of parallel programming; to be more precise, given some pieces of code, I have to determine which of them can be parallel and which cannot(this was in a test in a parallel programming class):

a) a=2; b=3;                    //yes-variables are independently initialised
b) a=3;b=a;                     //depends on the synchronisation
c) a=3;b=a;c=b;                 //depends on which gets executed first
d) b=a;c=b;a=4;                 //no-because some variables might get init to the new value while other to the old value
e) a=2;b=a+3;a=3;               //no-it's not clear to which value of 'a' the var. 'b' wil get calculated
f) for(i=0;i<100;i++) 
    b[i]=i;                     //yes- variable depends solely on the index
g) for(i=0;i<100;i++) 
    b[i]=f(b[i]);               //yes-variable doesn't depend on another variable
h) for(i=0;i<100;i++)
    for(j=0;j<100;j++)   
        b[i][j]= f(b[i][j-1]);  //no-current variable depends on previous 
i) a=f(x); b=g(x);              //variables get initialised independently
j) for(i=0;i<100;i++) 
    b[i] = f(b[index[i]]);      //same as i)

so my question is how far off am I from the correct answers ?
PS: if you like, you can contribute to the thread by posting questions(test questions, interviews etc.) of this type here as it might also help others

CPT
Light Poster
37 posts since Aug 2010
Reputation Points: 10
Solved Threads: 1
Skill Endorsements: 0

I found out that the MS MPI implementation suports at max MPI.Threading.Serialized, and on hovering the mouse over this initialisation mod VS shows me this:

Threading-Serialized
The program is multi-threaded,and more than one thread will amke calls into the MPI library. 
However, these calls into MPI are"serialzied", in that no two threadswill call the MPI library at the same time. 
This mode essentially requires the user program to have the equivalent of a global lock around all calls to MPI.
CPT
Light Poster
37 posts since Aug 2010
Reputation Points: 10
Solved Threads: 1
Skill Endorsements: 0

Open the visual studio in administrator mode and try it out

Well I did that, but still no change(in the tutorial it days that I need to run it from a command prompt, so from VS I just compile it)

Also I tried a recomended setting from another site for that error:Going in Tools->Options->Debuggin(General)->uncheck Supress JIT optimisation on module load...

CPT
Light Poster
37 posts since Aug 2010
Reputation Points: 10
Solved Threads: 1
Skill Endorsements: 0

Hello everyone, I've encounterred a problem that I cannot seem to overcome. For the program to compile there are a few steps necessary to take: from the website Click Here on the download page, one would need to download and install:

  1. MPI.NET SDK
  2. Microsoft Compute Cluster Pack SDK(this one is the one that I used,this needs to be installed in the x86 version of Program Files,this was the only solution that I found to be able to install it);
  3. Also there is a tutorial for installing the previous programs and a small introduction to the MPI program model (in C#)

Now follows the code that I've written:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MPI;
using System.Threading;


namespace _PRO__MAPC_MPI_Chat
{
    class Program
    {
        static void Main(string[] args)
        {
            using (new MPI.Environment(ref args))
            {
                int producersNo = 1;// (Communicator.world.Size - 1) / 2;
                // Console.WriteLine("number of producers :{0}",producersNo);
                Intracommunicator comm = Communicator.world;
                Random rand = new Random();
                if (comm.Rank == 0)
                {
                    // program for rank 0; in this case is the server/queue process
                    Queue<string> que = new Queue<string>();
                    const int MAXSIZE = 10;
                    string msg = null;
                    string response = null;
                    new Thread(() =>
                    {
                        while (true)
                        {
                            //get the message from entity
                            msg = comm.Receive<string>(Communicator.anySource, 0);
                            if ((msg == null) && (1 < msg.Length))
                            {
                                Console.WriteLine("Process Rank 0 Ended!");
                                break;
                            }
                            // Console.WriteLine("Queue process received a message !");
                            lock (que)
                            {
                                if (que.Count() != MAXSIZE)
                                {
                                    que.Enqueue(msg);
                                    Monitor.PulseAll(que);
                                }
                                else
                                {
                                    Console.WriteLine("Queue is full discarding received message: {0}", msg);
                                }
                            }
                        }
                    }).Start();
                    new Thread(() =>
                    {
                        while (true)
                        {
                            //get the message from Queue to the destination
                            lock (que)
                            {
                                while (que.Count == 0)
                                {
                                    Monitor.Wait(que);
                                }
                                response = que.Dequeue();
                            }
                            if (response != null)
                                comm.Send<string>(response, rand.Next(producersNo, comm.Size), 0);
                            else
                                Console.WriteLine("response is null!");
                        }
                    }).Start();
                }
                else // not rank 0(not the central node)
                {
                    int timeToSleepProducer = 900;
                    int timeToSleepConsumer = 1000;
                    Console.WriteLine(" Process Rank:{0} started", comm.Rank);
                    {
                        new Thread(() =>
                        {
                            //consume the received message
                            string received = null;
                            while (true)
                            {
                                received = comm.Receive<string>(0, 0);
                                if ((received == null) && (1 < received.Length))
                                {
                                    Console.WriteLine("Program Ended!");
                                    break;
                                }

                                Thread.Sleep(timeToSleepProducer);
                                Console.WriteLine("msg: \"{0}\" got consumed by {1}", received, Communicator.world.Rank);
                            }
                        }
                       ).Start();
                    }
                    // else
                    {
                        //execute producer code(create the messages)
                        // new Thread(() =>{
                            string msg = null;
                            while (true)
                            {
                                msg = DateTime.Now.ToString();
                                //msg = Console.ReadLine();
                                comm.Send<string>(msg, 0, 0);
                                if ((msg == null) && (1 < msg.Length))
                                {
                                    Console.WriteLine("Program Ended!");
                                    break;
                                }
                                Thread.Sleep(timeToSleepConsumer);
                                Console.WriteLine("msg: \"{0}\" produced by {1}", msg, Communicator.world.Rank);
                            }
                        //}).Start();
                    }
                }
            }
        }
    }
}

The most frequent error(and the stack trace) that I'm getting is:

Unhandled Exception: System.AccessViolationException: Attempted to read or write
 protected memory. This is often an indication that other memory is corrupt.
   at MPI.Unsafe.MPI_Send(IntPtr buf, Int32 count, Int32 datatype, Int32 dest, I
nt32 tag, Int32 comm)
   at MPI.Communicator.Send[T](T value, Int32 dest, Int32 tag)
   at MPI.Communicator.Send[T](T value, Int32 dest, Int32 tag)
   at _PRO__MAPC_MPI_Chat.Program.<>c__DisplayClass5.<Main>b__1() in E:\Programm
ing\Projects\MAPC_Proj\MAPC_Proj\Program.cs:line 68
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, C
ontextCallback callback, Object state)
   at System.Threading.ThreadHelper.ThreadStart()

If it matters: I'm using Visual Studio 2008.

CPT
Light Poster
37 posts since Aug 2010
Reputation Points: 10
Solved Threads: 1
Skill Endorsements: 0

i've just started learning the C# language and this is my first program to use threads.
I don't understand why the consumer thread doesn't get called( only after the producer has stopped)and when it gets called it doesn't consume anything, also I've noticed that the majority of produced elements are of the same values.
Here is the full code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;


namespace Sem_example_luci
{
    class Semaphore
    {
        private Object oLock;
        private int iResourceAccesses;
        private Boolean isBinary;
       // private LinkedList<Thread> vWaitingTh;
        private Semaphore()
        {
            this.oLock = new Object();
            //this.vWaitingTh = new LinkedList<Thread>();
        }
        public Semaphore(int initialSemaphoreCount)
            : this()
        {
            if (initialSemaphoreCount == 1)
                this.isBinary = true;
            this.iResourceAccesses = initialSemaphoreCount;
        }
        public void increase(Int32 iIncrement)
        {
            lock (this.oLock)
            {
                this.iResourceAccesses += iIncrement;
               // Console.WriteLine("Semaphore incremented");
                if (this.isBinary)
                {
                    Monitor.Pulse(this.oLock);
                }
            }
        }
        public void decrease(Int32 iDecrement)
        {
            lock (this.oLock)
            {
                while(this.iResourceAccesses == 0 && this.isBinary)
                {
                    //add thread to queue
                    Monitor.Wait(this.oLock);
                }
                //Console.WriteLine("semaphore decremented!");
                    this.iResourceAccesses -= iDecrement;
                   // Monitor.Pulse(oLock);
            }
        }
        class ElementaryItem
            //this class represents what gets produced and consumed
            //the element will be consumed only when the "priotity"
            //of the element equals that of the current priority
        {
            public static Int16[] priorities = { 0, 1, 2, 3, 4 };
            private Int32 ID, priority;

            public static Int32 getRandomPriority()
            {
                Random rand = new Random();
                Int32 temp = (priorities[priorities.Length - 1] - priorities[0] + 1);
                return rand.Next() % temp + priorities[0];
            }
            public ElementaryItem()
            {
                Random rand = new Random();
                this.ID = rand.Next(0, Int16.MaxValue);
                this.priority = rand.Next(priorities[0]-1,priorities[priorities.Length-1]+1);
            }
            public ElementaryItem(ElementaryItem o)
            {
                this.ID = o.ID;
                this.priority = o.priority;
            }
            public int getID()
            {
                return this.ID;
            }
            public int getPriority()
            {
                return this.priority;
            }
            public String toString()
            {
                return "Element ID: " + this.ID + "\t with priority:" + this.priority;
            }
        }
        class MyQueue
            //this class holds the information, it's common for the producer and consumer
        {
            private Int32 MaxNumberOfElements;
            private List<ElementaryItem> items;//the key will be the priority
            private static int currentPriority;
            public void putItemIntoQueue(ElementaryItem item)
            {
                this.items.Add(item);
                Console.WriteLine("Added in queue the item:"+item.toString());
                this.MaxNumberOfElements--;
                Console.WriteLine("new number of elements = " + this.MaxNumberOfElements);
            }
            public static void updatePriority(){
                while (true)
                {
                    //generate a random priority
                    MyQueue.currentPriority = (MyQueue.currentPriority+1) % ElementaryItem.priorities.Length;//we need the next priority
                    Console.WriteLine("Now serving priority level:{0}", MyQueue.currentPriority);
                    Thread.Sleep(10000);
                }
            }
            public ElementaryItem getItemFromQueue()
            {
                ElementaryItem retValue = null;
                for (int i = 0; i < this.items.Count; i++)
                {
                    ElementaryItem temp = this.items[i];

                    if (temp.getPriority() == MyQueue.currentPriority || i==this.items.Count)
                    {
                        retValue = new ElementaryItem(temp);//copy the element
                        this.items.RemoveAt(i);//remove the original
                        break;
                    }//else to prevent queue overflow we disregard the priority condition 
                     //and we just take the last visited element
                }
              //  Console.WriteLine("Remainig elements" + this.items.Count());
                return retValue;
            }
            public MyQueue(Int32 maxSize)
            {
                this.MaxNumberOfElements = maxSize;//the maximum numeber of elements we want to produce
                this.items = new System.Collections.Generic.List<ElementaryItem>();
                MyQueue.currentPriority = ElementaryItem.getRandomPriority();
                Thread priorityUpdate = new Thread(MyQueue.updatePriority);
                priorityUpdate.Start();
            }
            //this function
            public bool endConditionAchieved()
            {
                return this.MaxNumberOfElements == 0;
            }
        }
        class Entity
        {
            public enum EntityType { Producer, Consumer };
            private EntityType eType;
            private Semaphore emptyCount;//we keep track, using the semaphore, of the number of empty spaces
            private Semaphore fullCount;//and the number of elements currently on the queue
            private Semaphore useQueue;//binary semaphore
            private MyQueue elementQueue;
            public Entity(EntityType e, Semaphore emptyCount, Semaphore fullCount,Semaphore useQueue,MyQueue elementQueue)
            {
                this.eType = e;
                this.emptyCount = emptyCount;
                this.fullCount = fullCount;
                this.useQueue = useQueue;
                this.elementQueue = elementQueue;
            }
            public static void Worker(Object ent)
            {
            ((Entity)ent).action();
            }
            public void action()
            {
                if (this.eType == EntityType.Producer)
                {
                    Console.WriteLine("Thread producerr fired!");
                    this.produce();
                }
                else
                {
                    Console.WriteLine("Thread Consumer fired!");
                    this.consume();
                }
            }
            private void produce()
            {
                while (!this.elementQueue.endConditionAchieved())
                {
                   // Thread.Sleep(10000);
                    this.emptyCount.decrease(1);
                    //Console.WriteLine("emptyCount decreased");
                    this.useQueue.decrease(1);
                   // Console.WriteLine("useQueue decreased");
                    this.elementQueue.putItemIntoQueue(new ElementaryItem());
                   // Console.WriteLine("Element added to queue");
                    this.useQueue.increase(1);
                   // Console.WriteLine("useQueue increased");
                    this.fullCount.increase(1);
                   // Console.WriteLine("fullCount increased");
                }
            }
            private void consume()
            {
                Console.WriteLine("Consumer before while");
                //while (!this.elementQueue.endConditionAchieved())
                while(true)
                {
                   // Console.WriteLine("in the while loop");
                    this.fullCount.decrease(1);
                   // Console.WriteLine("fullCount decremented ");
                    this.useQueue.decrease(1);
                   // Console.WriteLine("useQueue decremented");
                    ElementaryItem item = this.elementQueue.getItemFromQueue();
                    if (item != null)
                    {
                        Console.WriteLine("Consumed item:"+ item.toString());
                    }
                   // Console.WriteLine("Element removed from queue!");
                    this.useQueue.increase(1);
                   // Console.WriteLine(" useQueue incremented");
                    this.emptyCount.increase(1);
                   // Console.WriteLine(" emptyCount incremented");
                }
            }
        }
        static void Main(string[] args)
        {
            int noElements = 10;
            int noProducers = 1;
            int noConsumers = 2;

            Semaphore emptyCount, fullCount, useQueue;
            emptyCount = new Semaphore(noElements);
            fullCount = new Semaphore(0);
            useQueue = new Semaphore(1);
            MyQueue elemQueue = new MyQueue(noElements);

            Entity[] producers = new Entity[noProducers];
            Entity[] consumers = new Entity[noConsumers];
            for(int i=0;i<producers.Length;i++){
                producers[i] = new Entity(Entity.EntityType.Producer,emptyCount,fullCount,useQueue,elemQueue);
                Thread th = new Thread(Entity.Worker);
                th.Start(producers[i]);
            }
            for(int i=0;i<consumers.Length;i++){
                consumers[i] = new Entity(Entity.EntityType.Consumer,emptyCount,fullCount,useQueue,elemQueue);
                Thread th = new Thread(Entity.Worker);
                th.Start(consumers[i]);
            }
            Console.ReadKey();//to view the results
        }
    }
}
CPT
Light Poster
37 posts since Aug 2010
Reputation Points: 10
Solved Threads: 1
Skill Endorsements: 0

line 36: this.sendMessage(new String(john").getBytes());
shouldn't it be in full quotations: "john"?

well in the program it is in full quotations, thanks for pointing that out

latest update: I've put the keyword volatille to the Socket member in the client(since it's shared resource between the main thread and the serverResponse) thread with no results: the socket still appears to be empty in the serverResponse thread.

CPT
Light Poster
37 posts since Aug 2010
Reputation Points: 10
Solved Threads: 1
Skill Endorsements: 0

I moved the main functino from the handle client in the server class, now it should work normally, I can't edit my previous post so here is the server :

package temp_server;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;


public class Server extends Thread{

    void StartServer(){
        ServerSocket ss = null;
        try{
            ss = new ServerSocket(4444);
            while(true){
                Socket sock = ss.accept();
                new handleClient(sock).start();
            }

        }catch(IOException e){
            e.printStackTrace();
            System.out.println("IOEception in startServer()!");
            System.exit(-1);
        }catch(Throwable th){
            th.printStackTrace();
        }
    }
    public void run(){
        this.StartServer();
    }

    public static void main(String[] args){
        Server server = new Server();
        server.start();
    }
}
class handleClient extends Thread{
    private Socket socket = null;
    private BufferedInputStream in = null;

    public handleClient(Socket sock)throws IOException{
        this.socket = sock;
        this.in =  new BufferedInputStream(socket.getInputStream());
    }
    public void run(){
        byte[] input = new byte[1024];
        try{
            in.read(input,0,input.length);
            //echoing back the message
            sendMessage(input);
        }
        catch(IOException e){
            System.out.println("IOEXCEPTION!!!!!");
        }
    }
    void sendMessage(byte[] tosend) throws IOException{
        OutputStream out = null;
        try {
            out = this.socket.getOutputStream();
            out.write(tosend, 0, tosend.length);

        } catch (IOException e) {
            // TODO Auto-generated catch block
            System.out.println("Exception in sendBytes()");
            e.printStackTrace();
        } finally {
            if (out != null) {
                out.flush();
                out.close();
            }
        }
    }
}

What is the code supposed to do when it does execute?

Well the client application sends a message to the server in the constructor, after that it should wait for a response from the server in serverResponse thread and print-out what it received. The server should handle the client conection in the handleClient thread, in which it should echo the message back to the client.

CPT
Light Poster
37 posts since Aug 2010
Reputation Points: 10
Solved Threads: 1
Skill Endorsements: 0

as an IDE I'm using eclipse: for some reason the only way I can get the server to run is by right click on the server's package and select run as java aplication.

CPT
Light Poster
37 posts since Aug 2010
Reputation Points: 10
Solved Threads: 1
Skill Endorsements: 0

so this a basic version of the client:

package temp_client;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;

public class Client extends Thread{
    Socket socket = null;
    serverResponse sr = null;
    private class serverResponse extends Thread{
        InputStream in = null;

        public serverResponse(Socket socket) throws IOException{
            if (socket == null) { System.out.println("socket:null");}
            this.in = socket.getInputStream();
        }

        public void run() {
            try {
                while (true) {
                    if (!socket.isClosed() || socket.isConnected()) {
                        byte[] input = new byte[1024];
                        // read the message
                        in.read(input, 0, input.length);
                        // unserialize and dispatch
                        for(int i=0;i<input.length;i++){
                            System.out.print("byte["+i+"]="+input[i]);
                        }
                    }
                }
            } catch (IOException ex) {
                System.out.println("IOException in waitForReplyFromServer");
                ex.printStackTrace();
            } finally {
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        }

    }
    public Client() throws Exception{
        this.socket =new Socket(InetAddress.getByName("localhost"), 4444);
        this.sendMessage(new String("john").getBytes());
        this.sr = new serverResponse(socket);

        this.sendMessage(new String("Hello world").getBytes());
    }
    void sendMessage(byte[] tosend) throws IOException{
        OutputStream out = null;
        try {
            out = this.socket.getOutputStream();
            out.write(tosend, 0, tosend.length);
            out.flush();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            System.out.println("Exception in sendBytes()");
            e.printStackTrace();
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }
    public void run(){
        this.sr.start();
    }
    public static void main(String args[]){
        Client c1;
        try {
            c1 = new Client();
            c1.start();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

and this is the server:

package temp_server;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;


public class Server extends Thread{

    void StartServer(){
        ServerSocket ss = null;
        try{
            ss = new ServerSocket(4444);
            while(true){
                Socket sock = ss.accept();
                new handleClient(sock).start();
            }

        }catch(IOException e){
            e.printStackTrace();
            System.out.println("IOEception in startServer()!");
            System.exit(-1);
        }catch(Throwable th){
            th.printStackTrace();
        }
    }
    public void run(){
        this.StartServer();
    }
}
class handleClient extends Thread{
    private Socket socket = null;
    private BufferedInputStream in = null;

    public handleClient(Socket sock)throws IOException{
        this.socket = sock;
        this.in =  new BufferedInputStream(socket.getInputStream());
    }
    public void run(){
        byte[] input = new byte[1024];
        try{
            in.read(input,0,input.length);
        }
        catch(IOException e){
            System.out.println("IOEXCEPTION!!!!!");
        }
    }
    void sendMessage(byte[] tosend) throws IOException{
        OutputStream out = null;
        try {
            out = this.socket.getOutputStream();
            out.write(tosend, 0, tosend.length);

        } catch (IOException e) {
            // TODO Auto-generated catch block
            System.out.println("Exception in sendBytes()");
            e.printStackTrace();
        } finally {
            if (out != null) {
                out.flush();
                out.close();
            }
        }
    }

    public static void main(String[] args){
        Server server = new Server();
        server.start();
    }
}
CPT
Light Poster
37 posts since Aug 2010
Reputation Points: 10
Solved Threads: 1
Skill Endorsements: 0

Did that fix the problem?

no
this program should send information to a server via sendBytes function, and wait for responses in the serverResponse thread/class, I don't understand why the socket is closed at that point because sendbytes sends information succesfuly to the server(which means that the socket shouldn't be closed)

CPT
Light Poster
37 posts since Aug 2010
Reputation Points: 10
Solved Threads: 1
Skill Endorsements: 0

someone correct me if I'm wrong: both bitwise and logical operators are the representation of the boolean function with the same names(better read on that first as I suspect the fact that you haven't) the diference is that the bitwise ones operate on bits(it doesn't matter if your data type has 8,16,32 or 64 bits, the operation is applied to every bit of the operands e.g 1|1 =1 10|01 =11, 100|1 = 101 and so on), where as the logical operators operate on logical atoms( the whole atom is considered as a bit, the interpreted values are false for 0 and true for non-zero values)

CPT
Light Poster
37 posts since Aug 2010
Reputation Points: 10
Solved Threads: 1
Skill Endorsements: 0

Is that right?

you are right, it was the other way around now it's the right way

CPT
Light Poster
37 posts since Aug 2010
Reputation Points: 10
Solved Threads: 1
Skill Endorsements: 0

Heloo,this wil be my first post here, the reason for that is I can't figure this one out by myself

public class Client extends Thread{
Socket socket = null;
ServerResponse sr = null;
    private class serverResponse extends Thread{
     InputStream in = null;
     public serverResponse(Socket socket) throws IOException{
         if (socket == null) { System.out.println("socket:null");}
          this.in = socket.getInputStream();
     }
     public void run() {
        try {
                while (true) {
                    if (!socket.isClosed() || socket.isConnected()) {
                    byte[] input = new byte[1024];
                    // read the message
                    in.read(input, 0, input.length);
                    // unserialize and dispatch
                    }
                }
                 } catch (IOException ex) {
                 System.out.println("IOException in waitForReplyFromServer");
                 ex.printStackTrace();
                 } finally {
                 if (in != null) {
                    try {
                        in.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
              }
           }
public client() throw Exception{
    this.socket =new Socket(InetAddress.getBytName("localhost", 4444); 
    this.sendMessage(new String(john").getBytes());
}
sendMessage(byte[] tosend){
    OutputStream out = null;
        try {
            out = this.socket.getOutputStream();
            out.write(bytesToSend, 0, bytesToSend.length);
            out.flush();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            System.out.println("Exception in sendBytes()");
            e.printStackTrace();
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }
public void run(){
    this.serverResponse.start();
}
}

Excepting for the lack of some client class members, this what my class looks like, the problem that I was referring about is I get an IOException :
IOException in waitForReplyFromServer
java.net.SocketException: socket closed
from this line line: in.read(input, 0, input.length);, the thing that confuses me the most is that is after the if-condition

CPT
Light Poster
37 posts since Aug 2010
Reputation Points: 10
Solved Threads: 1
Skill Endorsements: 0

You need to read up on serialization. Real serialization, not this shallow copy crap.

Well, I've tried to search with google and this is what I've found so far.I'm open to better serialization methods

CPT
Light Poster
37 posts since Aug 2010
Reputation Points: 10
Solved Threads: 1
Skill Endorsements: 0

so regarding my second question about sending it over a network; the v_friends,messages and groups fields are pointers to vectors, right?(so they will have only 4 bytes each ?) wouldn't that be a problem when I allocate a buffer with the size of the class(you know, to send it)?

Why the pointer in the first place? You could manage without it, can't you?

Well I think I can, but in this case I will need a default constructor for the class

CPT
Light Poster
37 posts since Aug 2010
Reputation Points: 10
Solved Threads: 1
Skill Endorsements: 0
class item
{
string name;
string identifier;
public:
  item( string name,string id):{this->name=name;this->identifier=id;}
        friend ostream& operator<<(ostream&, const item&);
        friend istream& operator>>(istream&, item&);
};
ostream& operator<<(ostream& out, const item& temp)
{
	out<<item.name<<" "<<item.identifier<<endl;
	return out;
}
istream& operator>>(istream& in, Cmessage& temp)
{
	getline(in,item.name);//in case sring has space char
	getline(in,item.identifier);

	return in;
}
class CGuser
{
	bool online;
	int score;
	string name;
	string password;
	string IP;
	vector<item> messages;
	vector<string> v_friends;
	vector<string> groups;
public:
        CGuser(string name, string password)	
       {	
        this->name=name;
        this->password=password;
        this->score=0;}
	friend ostream& operator<<(ostream&, const CGuser&);
	friend istream& operator>>(istream&, CGuser&);

ostream& operator<<(ostream& out, const CGuser& temp)
{
	int size;
	out<<temp.online<<endl;
	out<<temp.score<<endl;
	out<<temp.name<<endl;
	out<<temp.password<<endl;
	out<<temp.IP<<endl;

	size=temp.messages.size();
	out<<size<<" ";
	for(int i=0;i<size;i++)
		out<<temp.messages[i]<<endl;

	size=temp.v_friends.size();
	out<<size<<" ";
	for(int i=0;i<size;i++)
		out<<temp.v_friends[i]<<endl;

	size=temp.groups.size();
	out<<size<<" ";
	for(int i=0;i<size;i++)
		out<<temp.groups[i]<<endl;

	out<<endl;
	return out;
}
istream& operator>>(istream& in, CGuser& temp)
{
	int size;
	string stmp;
	Cmessage cmg;

	in>>temp.online;
	in>>temp.score;
	getline(in,temp.name);
	getline(in,temp.password);
	getline(in,temp.IP);

	in>>size;
	for(int i=0;i<size;i++)
	{
		in>>cmg;
		temp.messages.push_back(cmg);
	}

	in>>size;
	for(int i=0;i<size;i++)
	{
		getline(in,stmp);
		temp.v_friends.push_back(stmp);
	}
	
	in>>size;
	for(int i=0;i<size;i++)
	{
		getline(in,stmp);
		temp.groups.push_back(stmp);
	}
	
	return in;
}
};
CGuser *user;
string name,pass;

cout<<"enter name:"<<endl
cin>>name;
cout<<"enter password"<<endl;
cin>>pass;
user= new CGuser(name,pass,0);
cout<<user;

the problem is with the last line, and what I mean problem is than it prints a number(I suspect the address in memory where user is allocated)instead of each field of the class
Another question that I have is how do I send over the network first just the item class, then the CGuser class(both client and server are the same endianess)

CPT
Light Poster
37 posts since Aug 2010
Reputation Points: 10
Solved Threads: 1
Skill Endorsements: 0

I know that you can use assembly combined with C++(either inline or using modules written completely in assembly, linked with the rest of the program), and I was curious how does a program written in different programming languages(eg Mozilla Firefox)work, and how it gets built.

CPT
Light Poster
37 posts since Aug 2010
Reputation Points: 10
Solved Threads: 1
Skill Endorsements: 0

Heh, the last function looks great. Consider the possibility that (for some reason) you have only one valid button to draw. (Hint: the problem is actually in your Menu constructor, and has been discussed and re-discussed so many times in this forum that there's a sticky topic for it at the top of the C++ topic list!)

If the hint isn't helping, start inserting debug "cout <<" statements everywhere that makes sense, such as at the end of your Button constructor function to print out all the member values. Good luck!

Please correct me if my answer is wrong
so as you said, the function is actually functioning fine, since it get's to draw everything in the vector, the problem's what's in the vector
In the constructor I push in the vector a pointer to where memory was allocated, but because I delete the memory allocated in the previous loop(line 72->76) and set to NULL(and because the pointers in the vector have the same address, they will also point to NULL)such as only the last vector wasn't equal to NULL.
BTW: If i wanted to do something like this:

vector< String* > tmp(5);
...
tButton=new Button(imag1.c_str(),imag.c_str(),mask.c_str(),bt_position);
tmp=tButton;
...
this->v_button.swap(tmp);

unless I've had definde the '='operator for the class, it would fail, so how would I define it?

CPT
Light Poster
37 posts since Aug 2010
Reputation Points: 10
Solved Threads: 1
Skill Endorsements: 0
 
© 2013 DaniWeb® LLC
Page generated in 0.1309 seconds using 2.72MB