Click here to Skip to main content
15,892,005 members
Home / Discussions / C#
   

C#

 
AnswerMessage Closed Pin
8-May-17 23:27
harold aptroot8-May-17 23:27 
QuestionRedundent code in a class Pin
hussain.rao158-May-17 20:29
hussain.rao158-May-17 20:29 
AnswerRe: Redundent code in a class Pin
Richard MacCutchan8-May-17 21:06
mveRichard MacCutchan8-May-17 21:06 
GeneralRe: Redundent code in a class Pin
hussain.rao1511-May-17 23:56
hussain.rao1511-May-17 23:56 
GeneralRe: Redundent code in a class Pin
Richard MacCutchan12-May-17 0:24
mveRichard MacCutchan12-May-17 0:24 
AnswerRe: Redundent code in a class Pin
Gerry Schmitz9-May-17 6:17
mveGerry Schmitz9-May-17 6:17 
QuestionCan you speed up the calculation of programs using software methods and how much? Pin
Member 127091098-May-17 1:21
Member 127091098-May-17 1:21 
QuestionQuestiongame over the net - client crash Pin
Member 129316127-May-17 7:52
Member 129316127-May-17 7:52 
This program here plays a small question game over the network, it's multi-threading and is of course based on a server and a client. It's written in C# using windows forms for the client and just console for the server.

I have a problem when the client writes to the server when the user press on enter. On line 70 I try to write to the server but it seems that the connection is somehow closed before I do so because I get the following error:

System.IOEndOfStreamException: Unable to read beyond the end of the stream.
at System.IO.BinaryReader.ReadByte()
at System.IO.BinaryReader.7BitEncodedInt()
at System.IO.BinaryReader.ReadString()
at question_game_client.Form1.RunCLient() in somepath:line 112

When I press enter in the textbox it's supposed to write to the server and it does but it does it twice and the client crashes with the error above.

Client:

C#
using System;
    using System;
    using System.Windows.Forms;
    using System.Threading;
    using System.Net.Sockets;
    using System.IO;

    namespace question_game_client
    {
      public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private NetworkStream output; // stream for receiving data           
        private BinaryWriter writer; // facilitates writing to the stream    
        private BinaryReader reader; // facilitates reading from the stream  
        private Thread readThread; // Thread for processing incoming messages
        private string message = "";

        private void Form1_Load(object sender, EventArgs e)
        {
            readThread = new Thread(new ThreadStart(RunClient));
            readThread.Start();   
        }

        // close all threads associated with this application
        private void Form1_FormClosing(object sender,
           FormClosingEventArgs e)
        {
            //System.Environment.Exit(System.Environment.ExitCode);
        } // end method ChatClientForm_FormClosing

        // delegate that allows method DisplayMessage to be called
        // in the thread that creates and maintains the GUI       
        private delegate void DisplayDelegate(string message);

        // method DisplayMessage sets displayTextBox's Text property
        // in a thread-safe manner
        private void DisplayMessage(string message)
        {
            // if modifying displayTextBox is not thread safe
            if (displayTextBox.InvokeRequired)
            {
                // use inherited method Invoke to execute DisplayMessage
                // via a delegate                                       
                Invoke(new DisplayDelegate(DisplayMessage),
                   new object[] { message });
            } // end if
            else // OK to modify displayTextBox in current thread
                displayTextBox.Text += message;
        } // end method DisplayMessage

        // delegate that allows method DisableInput to be called 
        // in the thread that creates and maintains the GUI
        private delegate void DisableInputDelegate(bool value);

        // sends text the user typed to server
        private void inputTextBox_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                  // create objects for writing and reading across stream
               
                if (e.KeyCode == Keys.Enter && inputTextBox.ReadOnly == false)

                {
                    writer.Write(inputTextBox.Text);
                   
                    inputTextBox.Clear();
                   

                } // end if
            } // end try
            catch (SocketException)
            {
                displayTextBox.Text += "\nError writing object";
            } // end catch
        } // end method inputTextBox_KeyDown

        // connect to server and display server-generated text
        public void RunClient()
        {
            TcpClient client;

            // instantiate TcpClient for sending data to server
            try
            {
       
                // Step 1: create TcpClient and connect to server
                client = new TcpClient();
                client.Connect("127.0.0.1", 8190);

                // Step 2: get NetworkStream associated with TcpClient
                output = client.GetStream();

                // create objects for writing and reading across stream
                writer = new BinaryWriter(output);
                reader = new BinaryReader(output);

                // loop until server signals termination
                do
                {
                    // Step 3: processing phase
                    try
                    {
                        
                        DisplayMessage("\r\n" + message);
                        // read message from server        
                        message = reader.ReadString();
                    } // end try
                    catch (Exception e)
                    {
                        // handle exception if error in reading server data
                        //System.Environment.Exit(System.Environment.ExitCode);

                        MessageBox.Show(e.ToString());
                    } // end catch
                } while (message != "SERVER>>> TERMINATE");

                // Step 4: close connection
                writer.Close();
                reader.Close();
                output.Close();
                client.Close();

                //Application.Exit();
            } // end try
            catch (Exception error)
            {
                // handle exception if error in establishing connection
                MessageBox.Show(error.ToString(), "Connection Error",
                   MessageBoxButtons.OK, MessageBoxIcon.Error);
                  // Environment.Exit(Environment.ExitCode);
            } // end catch
        } // end method RunClient

        private void inputTextBox_TextChanged(object sender, EventArgs e)
        {

        }
    }


    }

Server:

C#
using System;
    using System.Threading;
    using System.Net;
    using System.Net.Sockets;
    using System.Collections.Generic;
    using System.IO;

    namespace question_game_server
    {
    

    class Program
    {
        private Socket connection; // Socket for accepting a connection
        private int port = 8190;
        private Random rand = new Random();
        string message = null;
        string answer = null;

        static void Main(string[] args)
        {
            new Program().Run();
        }

        void Run()
        {
            new Thread(RunServer).Start();
            getquestions();
        }

        public void RunServer()
        {

            Thread readThread; // Thread for processing incoming messages
            bool done = false;

            TcpListener listener;
            try
            {

                // Step 1: create TcpListener
                //IPAddress local = IPAddress.Parse("127.0.0.1");
                listener = new TcpListener(IPAddress.Any, port);
                listener.Start();
                Console.WriteLine("Waiting for connection ...");

                while (!done)
                {
                    // This is where the server sits and waits for clients
                    connection = listener.AcceptSocket();
                   
        
                    // Start a new thread for a client
                    readThread = new Thread(GetMessages);
                    readThread.Start();
                }
            }
            catch (Exception)
            {
                Console.WriteLine("Port " + port + " may be busy. Try another.");
            }
        }
       
        //Reads the file with the questions and splits the question and the answer into two arrays.
        //Each question ends with ; and there is a : between each question and answer.
        public string getquestions()
        {
            int countquestions;
            int random_question_val;
           

            try
            {   // Open the text file using a stream reader.
                using (StreamReader sr = new StreamReader("questions_and_answers.txt"))
                {
                    // Read the stream to a string, and write the string to the console.
                    String line = sr.ReadToEnd();

                    string[] questions_and_answers = line.Split(';');

                    //Counts the questions
                    countquestions = questions_and_answers.Length-1;

                    random_question_val = rand.Next(0, (countquestions));

                    Console.WriteLine(random_question_val);

                    //Splits the answer ans the question
                    string[] question_and_answer = questions_and_answers[random_question_val].Split(':');

  
                    //The Answer

                    Console.WriteLine("Answer:"+question_and_answer[1]);

                    answer = question_and_answer[1];
              
                   
                    sr.Close();

                    //The question
                    return question_and_answer[0];

                   
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("The file could not be read:");
                Console.WriteLine(e.Message);
                return null;
            }

        }

       

        public void GetMessages()
        {
            Socket socket = connection;
            NetworkStream socketStream = null;
            BinaryWriter writer = null;
            BinaryReader reader = null;

            try
            {
                // establish the communication streams
                socketStream = new NetworkStream(socket);
                reader = new BinaryReader(socketStream);
                writer = new BinaryWriter(socketStream);
          
                Console.WriteLine("Connection successful.\n");
               
                writer.Write(getquestions());
                  
                message = reader.ReadString();

                Console.WriteLine(message);

                if (answer == message)

                {
                    writer.Write("Correct Answer!");
                    Console.WriteLine(message);
                }

                if (answer != message && message != null)
                {
                    Console.WriteLine(message);
                    writer.Write("Wrong Answer!");
                }

            }


            catch (Exception error)
            {
                Console.WriteLine(error.ToString());
            }

            finally
            {
                reader.Close();
                writer.Close();
                socketStream.Close();
                socket.Close();
            }
              Console.ReadKey();
        }

          


        }
    }


I guess it has a very simple explanation, I just can't see it. The only thing I know that this happens when I try to write to the server and the program is complaining about some reading issues. So what's wrong?

[edit]Code block added - OriginalGriff[/edit]

modified 8-May-17 3:38am.

AnswerRe: Questiongame over the net - client crash Pin
Richard Andrew x647-May-17 11:32
professionalRichard Andrew x647-May-17 11:32 
AnswerRe: Questiongame over the net - client crash Pin
OriginalGriff7-May-17 21:41
mveOriginalGriff7-May-17 21:41 
QuestionCreate Dynamic buttons Pin
Member 131834647-May-17 0:31
Member 131834647-May-17 0:31 
QuestionRe: Create Dynamic buttons Pin
CHill607-May-17 0:33
mveCHill607-May-17 0:33 
AnswerRe: Create Dynamic buttons Pin
User 41802547-May-17 8:49
User 41802547-May-17 8:49 
GeneralRe: Create Dynamic buttons Pin
Member 131834648-May-17 1:04
Member 131834648-May-17 1:04 
SuggestionRe: Create Dynamic buttons Pin
Richard Deeming8-May-17 1:54
mveRichard Deeming8-May-17 1:54 
QuestionHow to Do Implementation of this questions Please Pin
Member 131757266-May-17 11:08
Member 131757266-May-17 11:08 
AnswerRe: How to Do Implementation of this questions Please Pin
Mycroft Holmes6-May-17 14:00
professionalMycroft Holmes6-May-17 14:00 
AnswerRe: How to Do Implementation of this questions Please Pin
Pete O'Hanlon6-May-17 22:00
mvePete O'Hanlon6-May-17 22:00 
Questionanother way Type 'short is short-shrifted, but not short-shifted Pin
BillWoodruff5-May-17 1:10
professionalBillWoodruff5-May-17 1:10 
AnswerRe: another way Type 'short is short-shrifted, but not short-shifted Pin
Jochen Arndt5-May-17 1:32
professionalJochen Arndt5-May-17 1:32 
AnswerRe: another way Type 'short is short-shrifted, but not short-shifted Pin
Pete O'Hanlon5-May-17 1:35
mvePete O'Hanlon5-May-17 1:35 
AnswerRe: another way Type 'short is short-shrifted, but not short-shifted Pin
harold aptroot5-May-17 3:05
harold aptroot5-May-17 3:05 
GeneralRe: another way Type 'short is short-shrifted, but not short-shifted Pin
BillWoodruff5-May-17 4:54
professionalBillWoodruff5-May-17 4:54 
GeneralRe: another way Type 'short is short-shrifted, but not short-shifted Pin
harold aptroot5-May-17 5:19
harold aptroot5-May-17 5:19 
GeneralRe: another way Type 'short is short-shrifted, but not short-shifted Pin
BillWoodruff5-May-17 7:44
professionalBillWoodruff5-May-17 7:44 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.