C#中的TCP客户端服务器应用程序帮助 [英] Help in TCP Client Server Application in C#

查看:77
本文介绍了C#中的TCP客户端服务器应用程序帮助的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,
我已经在c#visual studio 2005中创建了一个TCP客户端服务器应用程序,以在服务器中广播随机生成的float值并将其发送给客户端.客户需要提供用户名和密码来接收该值.对于一个客户端,它可以正常工作,但是如果添加了另一个客户端,则该程序将失败.
您能帮我吗?

谢谢
阿尔潘

服务器代码:

Hello,
I have created a TCP client server application in c# visual studio 2005 to broadcast a randomly generated float value in server and send to client. client requires to give the username and password to recieve the value. It works fine for one client but if another client is added the program fails.
can you please help me with this.

Thank you
Arpan

Server code:

using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.IO;
namespace server
{
    public class login
    {
        Socket s;

        public login(Socket valueS)
        {
            s = valueS;
        }

        public void check()
        {
            try
            {

                byte[] uname = new byte[100];
                byte[] pword = new byte[100];
                int sizeuser = s.Receive(uname);
                int sizepword = s.Receive(pword);

                if (sizeuser > 0 && sizepword > 0)
                {
                    Console.WriteLine("Recieved");
                    TextReader objTxtReader = new StreamReader("login.txt");
                    String username = objTxtReader.ReadLine();
                    String password = objTxtReader.ReadLine();
                    String test = ASCIIEncoding.ASCII.GetString(uname);
                    test = test.Substring(0, sizeuser);
                    if (username == (ASCIIEncoding.ASCII.GetString(uname)).Substring(0, sizeuser) && password == (ASCIIEncoding.ASCII.GetString(pword)).Substring(0, sizepword))
                    {

                    }
                    else
                    {
                        ASCIIEncoding asen2 = new ASCIIEncoding();
                        s.Send(asen2.GetBytes("0"));
                    }

                }

            }
        catch(Exception e){  }

        }

    }


    public  class Program
    {
      
        static void Main(string[] args)
        {
            try
            {
                IPAddress ipAd = IPAddress.Parse("192.168.10.68");
                TcpListener myList = new TcpListener(ipAd, 8002);
                myList.Start();
                Random randDouble = new Random();
                double randValue;
                Socket s = myList.AcceptSocket();
                login objLogin = new login(s);
                Thread thdLogin = new Thread(new ThreadStart(objLogin.check));
                thdLogin.Start();
                thdLogin.Join();
                while (true)
                {
                randValue = randDouble.NextDouble();
                Console.WriteLine(randValue);
                Thread.Sleep(500);
                ASCIIEncoding asen = new ASCIIEncoding();
                String strRandValue = randValue.ToString();
                byte[] msg = asen.GetBytes(strRandValue);
                s.Send(msg);
                }
                s.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine("Error..... " + e.StackTrace);
            }
        }
    }
}




客户代码:




Client Code:

using System.Collections.Generic;
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Net.Sockets;
using System.Threading;
namespace client
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                TcpClient tcpclnt = new TcpClient();
                Console.WriteLine("Connecting.....");
                String username=null;
                String password= null;

                tcpclnt.Connect("192.168.10.68", 8002);
                Console.WriteLine("Connected");
                Console.WriteLine("Enter Username");
                username =  Console.ReadLine();
                Console.WriteLine("Enter Password");
               // password =  Console.ReadLine();
                ConsoleKeyInfo key;
                do
                {
                    key = Console.ReadKey(true);
                    if (key.Key != ConsoleKey.Backspace && key.Key != ConsoleKey.Enter)
                    {
                        password += key.KeyChar;
                        Console.Write("*");
                    }
                    else
                    {
                        if (key.Key == ConsoleKey.Backspace && password.Length > 0)
                        {
                            password = password.Substring(0, (password.Length - 1));
                            Console.Write("\b \b");
                        }
                    }
                }while(key.Key!=ConsoleKey.Enter);

                Console.Write("\n");
                Stream stm = tcpclnt.GetStream();
                ASCIIEncoding uname = new ASCIIEncoding();
                byte[] byteUsername = uname.GetBytes(username);
                ASCIIEncoding pword = new ASCIIEncoding();
                byte[] bytePword = uname.GetBytes(password);
                stm.Write(byteUsername, 0, byteUsername.Length);
                stm.Write(bytePword, 0, bytePword.Length);

                byte[] byteMsg = new byte[100];
                int length = stm.Read(byteMsg, 0, 100);
                while (length>1)
                {
                    for (int i = 0; i < length; i++)
                    Console.Write(Convert.ToChar(byteMsg[i]));
                    Console.WriteLine("\n");
                    length = stm.Read(byteMsg, 0, 100);
                }  
                 
                if (length == 1)
                {
                    Console.WriteLine("Invalid username or password");
                }
                tcpclnt.Close();
                String str1 = Console.ReadLine();
            }

            catch (Exception e)
            {
                Console.WriteLine("Error..... " + e.StackTrace);
            }
        }
    }
}

推荐答案

如果您想接受多个连接,那么您应该使用...

If you want to accept multiple connections then you should have code kind of ...

while( true )
{
SOCKET soc = AcceptSocket ()

Create a thread and send the soc object to that thread. 
}



这个故事的寓意是,

您的服务器应接受该连接,并将与该连接关联的工作委托给线程.
您的主程序应该是免费的,并等待连接.

在您的情况下,您只需调用一次AcceptSocket.这就是为什么您能够首次连接它的原因.
第二次,由于服务器端没有人正在等待连接,因此失败了.



Moral of the story is ,

Your server should accept the connection and should delegate the work associated with the connection to thread.
You main program should be free and wait for the connection.

In your case , you are calling AcceptSocket just once. This is why you are getting able to connect it first time.
Second time , as there is no one at server side is waiting for connection, it is failing.


这些可以为您提供帮助..
http://www.adventurespiele.net/module-pnForum-viewtopic-topic- 2704-start-0.htm [ ^ ]
C#.NET中完整的TCP Server/客户端通信和RMI框架-实施 [ ^ ]
These can help you..
http://www.adventurespiele.net/module-pnForum-viewtopic-topic-2704-start-0.htm[^]
A Complete TCP Server/Client Communication and RMI Framework in C# .NET - Implementation[^]


这篇关于C#中的TCP客户端服务器应用程序帮助的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆