Click here to Skip to main content
16,018,294 members
Please Sign up or sign in to vote.
2.50/5 (2 votes)
I have written one simple chat application which executes perfectly on single machine. When I am using this code in a LAN it behaves in strange pattern and fails in connecting to the server. In client window my port no is always 8081 which is specify in server code,and ip add is server machine address. I am posting my code here..
please help me..

Server code..
Window1.xaml
<pre lang="xml"><Window x:Class="TeacherWPF.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Server" Height="300" Width="300" Closed="Window_Closed">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="23*" />
            <ColumnDefinition Width="255*" />
            <ColumnDefinition Width="0*" />
        </Grid.ColumnDefinitions>
        <ListView Height="114" Margin="10,10,9,0" Name="lstView" VerticalAlignment="Top" Grid.ColumnSpan="2">
            <ListView.View>
                <GridView>
                    <GridViewColumn Header="ID" Width="40"></GridViewColumn>
                    <GridViewColumn Header="User Name" Width="100"></GridViewColumn>
                </GridView>
            </ListView.View>
        </ListView>
        <Label Margin="59,0,76,70" Name="label1" Height="28" VerticalAlignment="Bottom" Grid.Column="1"></Label>
    </Grid>
</Window

>



Window1.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Net;
using System.Net.Sockets;
using System.Collections;
using System.Threading;


namespace TeacherWPF
{
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class Window1 : Window
    {
        private int MaxConnected = 400;

        private Encoding ASCII = Encoding.ASCII;
        private static int connectId = 0;

        private TcpListener tcpLsn;
        private Hashtable socketHolder = new Hashtable();
        private Hashtable threadHolder = new Hashtable();
        private Hashtable userHolder = new Hashtable();
        Thread tcpThd;
        bool keepUser;
        public Window1()
        {
            InitializeComponent();
            IPAddress ipAdd = IPAddress.Parse("192.168.1.3");
            tcpLsn = new TcpListener(ipAdd,8081);
            tcpLsn.Start();
            tcpThd = new Thread(new ThreadStart(WaitingForClient));
            threadHolder.Add(connectId, tcpThd);
            tcpThd.Start();

        }
       
        public void WaitingForClient()
        {
            while (true)
            {
                // Accept will block until someone connects
                Socket sckt = tcpLsn.AcceptSocket();
                if (connectId < 10000)
                    connectId++;
                else
                    connectId = 1;
                if (socketHolder.Count < MaxConnected)
                {
                    while (socketHolder.Contains(connectId))
                    {
                        Interlocked.Increment(ref connectId);
                    }
                    Thread td = new Thread(new ThreadStart(ReadSocket));
                    lock (this)
                    {
                        // it is used to keep connected Sockets
                        socketHolder.Add(connectId, sckt);
                        // it is used to keep the active thread
                        threadHolder.Add(connectId, td);
                    }
                    
                    td.Start();
                }
            }
        }
        public void ReadSocket()
        {
            // realId will be not changed for each thread, 
            // but connectId is changed. it can't be used to delete object from Hashtable
            int realId = connectId;
            Socket s = (Socket)socketHolder[realId];
            while (true)
            {
                if (s.Connected)
                {
                    Byte[] receive = new Byte[37];
                    try
                    {
                        // Receive will block until data coming
                        // ret is 0 or Exception happen when Socket connection is broken
                        int ret = s.Receive(receive, receive.Length, 0);


                        if (label1 != null)
                        {

                        }
                        string tmp = null;
                        tmp = System.Text.Encoding.ASCII.GetString(receive);
                        string[] strArry = tmp.Split(':');
                        Dispatcher.BeginInvoke(new Action(() => label1.Content = strArry[0]), null);
                        Dispatcher.BeginInvoke(new Action(() => lstView.Items.Add(strArry[0])), null);

                        //Dispatcher.BeginInvoke(new Action(() => lstView.Items.Add(), null);

                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.ToString());
                        if (!s.Connected)
                        {
                            //this.lstView.Items[ind].ImageIndex = 1;
                            keepUser = false;
                            break;
                        }
                    }
                }
            }
            CloseTheThread(realId);
        }

        private int checkUserInfo(string userId)
        {
            //  check the userId and password first
            // ....

            if (true)// suppose it ok
            {
                if (userHolder.ContainsValue(userId))
                {
                    keepUser = true;
                    return 1; // user is login already
                }
            }
            return 2; // user is vailidate
        }
        private void CloseTheThread(int realId)
        {
            lock (this)
            {
                if (!keepUser) userHolder.Remove(realId);
                Thread thd = (Thread)threadHolder[realId];
                socketHolder.Remove(realId);
                threadHolder.Remove(realId);
                if (thd.IsAlive)
                    thd.Abort();
            }
        }
		private void SendDataToAllClient(string str)
		{
			foreach (int sKey in socketHolder.Keys) 
			{
				Socket s = (Socket)socketHolder[sKey];
				if(s.Connected)
				{
					Byte[] byteData = ASCII.GetBytes(str.ToCharArray());
					try
					{
						s.Send(byteData, byteData.Length, 0);
					}
					catch
					{
						// remove the bad client
						CloseTheThread(sKey);
					}
				}
			}
		}

      
        /*private void UpdateListView()
        {
            lock (this)
            {
                int ind = -1;
                for (int i = 0; i < this.lstView.Items.Count; i++)
                {
                    if (this.lstView.Items[i].ToString() == isu.symbol.ToString())
                    {
                        ind = i;
                        break;
                    }
                }
            }
        }*/
    }
}



ClientCode..

Window1.xaml
<pre lang="xml"><Window x:Class="StudentWPF.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300">
    <Grid>
        <Button Height="23" HorizontalAlignment="Left" Margin="10,10,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click">Button</Button>
    </Grid>
</Window

>



Window1.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Net;
using System.Net.Sockets;
using System.Threading;


namespace StudentWPF
{

    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class Window1 : Window
    {
        private Encoding ASCII = Encoding.ASCII;
        private Thread t;
        private Socket s;
        //Issue isu = new Issue();

        public Window1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            
            //ConnectDlg myDlg = new ConnectDlg();
           // myDlg.ShowDialog();
            Connect c = new Connect();
            c.ShowDialog();
            //if (myDlg.DialogResult == "OK")
            //{
                s = new Socket(AddressFamily.InterNetwork, SocketType.Stream,
                    ProtocolType.Tcp);

                IPAddress hostadd = IPAddress.Parse(c.IpAdd);
                int port = Int32.Parse(c.PortNum);
                IPEndPoint EPhost = new IPEndPoint(hostadd, port);

                try
                {
                    s.Connect(EPhost);

                    if (s.Connected)
                    {
                        Byte[] bBuf;
                        string buf;
                        buf = String.Format("{0}:{1}", c.UserName, c.PassWord);
                        bBuf = ASCII.GetBytes(buf);
                        s.Send(bBuf, 0, bBuf.Length, 0);
                        t = new Thread(new ThreadStart(StartRecieve));
                        t.Start();
                        //sbar.Text = "Ready to recieve data";
                        //menuConn.Enabled = false;
                    }
                }
                catch (Exception e1)
                {
                    MessageBox.Show(e1.ToString());
                }
            //}
        }
        private void StartRecieve()
        {
            //miv = new MethodInvoker(this.UpdateListView);
            int cnt = 0;
            string tmp = null;
            Byte[] firstb = new Byte[1];
            while (true)
            {
                try
                {
                    Byte[] receive = new Byte[1];
                    int ret = s.Receive(receive, 1, 0);
                    if (ret > 0)
                    {
                        switch (receive[0])
                        {
                            case 11: //check start message
                                cnt = 0;
                                break;
                            /*case 10: // check end message
                                cnt = 0;
                                if (firstb[0] == ':')
                                    HandleCommand(tmp);
                                else if (firstb[0] == '<')
                                    HandleXml(tmp);
                                else
                                    HandleText(tmp);
                                tmp = null;
                                break;*/
                            default:
                                if (cnt == 0)
                                    firstb[0] = receive[0];
                                tmp += System.Text.Encoding.ASCII.GetString(receive);
                                cnt++;
                                break;
                        }
                    }
                }
                catch
                {
                    if (!s.Connected)
                    {
                        //menuConn.Enabled = true;
                        break;
                    }
                }
            }
            t.Abort();
        }
    }

}


connect.xaml
<pre lang="xml"><Window x:Class="StudentWPF.Connect"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Connect" Height="324" Width="386">
    <Grid>
        <TextBox Height="23" Margin="124,26,120,0" Name="ip" VerticalAlignment="Top" />
        <TextBox Height="23" Margin="124,72,120,0" Name="pt" VerticalAlignment="Top" />
        <TextBox Margin="124,0,120,134" Name="UName" Height="23" VerticalAlignment="Bottom" />
        <TextBox Height="23" Margin="124,0,120,91" Name="PWord" VerticalAlignment="Bottom" />
        <Button Height="23" HorizontalAlignment="Left" Margin="87,0,0,29" Name="button1" VerticalAlignment="Bottom" Width="75" Click="button1_Click">coonnect</Button>
        <Button Height="23" HorizontalAlignment="Right" Margin="0,0,80,29" Name="button2" VerticalAlignment="Bottom" Width="75" Click="button2_Click">exit</Button>
        <Label Height="28" HorizontalAlignment="Left" Margin="12,21,0,0" Name="label1" VerticalAlignment="Top" Width="97">IP address</Label>
        <Label Height="28" HorizontalAlignment="Left" Margin="12,72,0,0" Name="label2" VerticalAlignment="Top" Width="106">Port no</Label>
        <Label HorizontalAlignment="Left" Margin="12,124,0,134" Name="label3" Width="106">user name</Label>
        <Label HorizontalAlignment="Left" Margin="7,0,0,91" Name="label4" Width="111" Height="28" VerticalAlignment="Bottom">Password</Label>
    </Grid>
</Window

>



connect.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace StudentWPF
{
    /// <summary>
    /// Interaction logic for Connect.xaml
    /// </summary>
    public partial class Connect : Window
    {
        private string username;
        private string password;
        private string ipAdd;
        private string port;
        public string UserName
        {
            get { return username; }
            set
            {
                username = value;
                UName.Text = username;
            }
        }
        public string PassWord
        {
            get { return password; }
            set
            {
                password = value;
                PWord.Text = password;
            }
        }
        public string PortNum
        {
            get { return port; }
            set
            {
                port = value;
                pt.Text = port;
            }
        }
        public string IpAdd
        {
            get { return ipAdd; }
            set
            {
                ipAdd = value;
                ip.Text = ipAdd;
            }
        }
        public Connect()
        {
            InitializeComponent();
        }
        private System.ComponentModel.Container components = null;
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            UserName = UName.Text;
            PassWord = PWord.Text;
            ipAdd = ip.Text;
            port = pt.Text;
            this.Close();
        }
        private void button2_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }
    }
}
Posted
Updated 3-May-11 20:17pm
v3
Comments
Ed Nutting 4-May-11 2:28am    
I don't have time to solve your problem now but you may be interested in my two articles on this topic:
http://www.codeproject.com/KB/game/FastNetworkingLibrary.aspx (Latest/Best)
http://www.codeproject.com/KB/IP/EasyToUseNetworkGaming.aspx (Old code but perhaps with better explaination of the basics)

1 solution

I have a Chat application sample.It's written by my own code.Source code is : http://hotfile.com/dl/116718226/5337ff9/Soket_CHAT.rar.html[^]
 
Share this answer
 
Comments
vishal_h 5-May-11 0:53am    
its in visual studio 2010 but i want in 2008..plz do u hava any code in visual studio 2010..
SercanOzdemir 5-May-11 5:41am    
Install 2010 then :/
SercanOzdemir 5-May-11 5:41am    
Or just examine CS files.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900