Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sockets/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 套接字单客户端/服务器连接,服务器可以发送多次,客户端只能发送一次_C#_Sockets_Connection_Client Server - Fatal编程技术网

C# 套接字单客户端/服务器连接,服务器可以发送多次,客户端只能发送一次

C# 套接字单客户端/服务器连接,服务器可以发送多次,客户端只能发送一次,c#,sockets,connection,client-server,C#,Sockets,Connection,Client Server,我已经编写了一个客户端和服务器应用程序,我需要用它连接我用C#制作的跳棋游戏。我已经让客户端和服务器连接,服务器可以重复发送客户端消息以更新标签,但是当客户端尝试发送消息时,它会抛出错误 “不允许发送或接收数据的请求,因为套接字未连接,并且(使用sendto调用在数据报套接字上发送时)未提供地址。” 这是到目前为止我的客户机和服务器 客户- public partial class Form1 : Form //main form that establishes connection {

我已经编写了一个客户端和服务器应用程序,我需要用它连接我用C#制作的跳棋游戏。我已经让客户端和服务器连接,服务器可以重复发送客户端消息以更新标签,但是当客户端尝试发送消息时,它会抛出错误

“不允许发送或接收数据的请求,因为套接字未连接,并且(使用sendto调用在数据报套接字上发送时)未提供地址。”

这是到目前为止我的客户机和服务器

客户-

public partial class Form1 : Form //main form that establishes connection
{
    Form2 form2 = new Form2();
    Socket sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    Socket acc = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    IPEndPoint endPoint;
    static byte[] Buffer { get; set; }
    string text;
    public Form1()
    {
        InitializeComponent(); 
    }

    private void button1_Click_1(object sender, EventArgs e)
    {
        Thread rec = new Thread(recMsg); 
        Thread t = new Thread(ThreadProc);
        t.Start(); //starts a form that will call the sendMsg on a button click
        endPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8887);

        try
        {   
            sck.Connect(endPoint);
        }
        catch
        {
            Console.WriteLine("unable to connect");
        }
        rec.Start();
        text = textBox1.Text;
        sendMsg(text);
    }
    public void sendMsg(string s)
    {
        //bool x = true;
        //while (true)
        //{
            //Thread.Sleep(500);
            //if (x == true)
            //{
                byte[] msgBuffer = Encoding.ASCII.GetBytes(s);
                sck.Send(msgBuffer); //error comes here when i try to send a message from form2 says it isn't connected and has no address
               // x = false;
            //}
        //} the commented out part doesn't effect how the send works it sends once and can't again, I think the problem is that the thread which establishes the connection dies but don't know how to solve.
    }

    public void recMsg()
    {
        while (true)
        {
            Thread.Sleep(500);
            byte[] Buffer = new byte[255];
            int rec = sck.Receive(Buffer, 0, Buffer.Length, 0);
            Array.Resize(ref Buffer, rec);
            form2.SetText(Encoding.Default.GetString(Buffer));
        }
    }

    private void button2_Click(object sender, EventArgs e)
    {
        sck.Close();
    }
    public void ThreadProc()
    {
        form2.ShowDialog();
    }
}
具有label1、textbox1和button1的表单2,主要操作表单将接受输入并调用Form1 sendMsg()

服务器-

class Program
{
    static Form1 form1 = new Form1();
    static Form2 form2 = new Form2();
    static byte[] buffer { get; set; }
    static Socket sck, acc;
    static string name;

    static void Main(string[] args)
    {
        if (name == null)
        {
            Thread t = new Thread(ThreadProc);
            t.Start();
        }
        Thread rec = new Thread(recMsg); 
        sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        sck.Bind(new IPEndPoint(0, 8887));
        Console.WriteLine("Your local IP address is: " + getIP());
        Console.WriteLine("Awaiting Connection");
        sck.Listen(0);

        acc = sck.Accept();
        Console.WriteLine(" >> Accept connection from client");
        rec.Start();
        sendMsg();
    }

    static string getIP()
    {
        string hostName = System.Net.Dns.GetHostName();
        IPHostEntry ipEntry = System.Net.Dns.GetHostEntry(hostName);
        IPAddress[] addr = ipEntry.AddressList;
        return addr[addr.Length - 1].ToString();
    }

    static void recMsg()
    {
        while (acc.Connected)
        {
            Thread.Sleep(500);
            byte[] Buffer = new byte[255];
            int rec = acc.Receive(Buffer, 0, Buffer.Length, 0);
            Array.Resize(ref Buffer, rec);
            form2.SetText(Encoding.Default.GetString(Buffer));
        }
    }

    public void btnClick(string s)
    {
        name = s;
        Console.WriteLine("Name: " + name);
        System.Threading.Thread r = new System.Threading.Thread(new System.Threading.ThreadStart(ThreadProc2));
        r.Start();
    }
    public void sendMSG(string s)
    {
            try
            {
                buffer = Encoding.Default.GetBytes(s);
                acc.Send(buffer);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
    }

    static void sendMsg()
        {
            try
            {
                buffer = Encoding.Default.GetBytes(name);
                acc.Send(buffer);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
    }

    public static void ThreadProc()
    {
        form1.ShowDialog();
    }

    public static void ThreadProc2()
    {
        form2.ShowDialog();
    }
}
using System;
using System.Net.Sockets;
using System.Text;
using System.Net;
using System.Threading;
using System.Windows.Forms;

namespace testServer
{
class Program
{
    static Form1 form1 = new Form1();
    static Form2 form2 = new Form2();
    static byte[] buffer { get; set; }
    static Socket sck, acc;
    static string name;

    public void setName(string s)
    {
        name = s;
        string[] asdf = new string[2];
    }

    static string getIP()
    {
        string hostName = System.Net.Dns.GetHostName();
        IPHostEntry ipEntry = System.Net.Dns.GetHostEntry(hostName);
        IPAddress[] addr = ipEntry.AddressList;
        return addr[addr.Length - 1].ToString();
    }

    static void Main(string[] args)
    {
        if (name == null)
        {
            Thread t = new Thread(ThreadProc);
            t.Start();
        } 
        sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        sck.Bind(new IPEndPoint(0, 8888));
        Console.WriteLine("Your local IP address is: " + getIP());
        Console.WriteLine("Awaiting Connection");
        sck.Listen(100);

        acc = sck.Accept();
        Console.WriteLine(" >> Accept connection from client");
        sendMsg();
        while (acc.Connected)
        {
            Thread.Sleep(500);
            byte[] Buffer = new byte[255];
            int receive = acc.Receive(Buffer, 0, Buffer.Length, 0);
            Array.Resize(ref Buffer, receive);
            form2.SetText(Encoding.Default.GetString(Buffer));
        }
    }
    public void btnClick(string s)
    {
        name = s;
        Console.WriteLine("Name: " + name);
        System.Threading.Thread r = new System.Threading.Thread(new System.Threading.ThreadStart(ThreadProc2));
        r.Start();
    }
    public void sendMSG(string s)
    {
            try
            {
                buffer = Encoding.Default.GetBytes(s);
                acc.Send(buffer);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
    }

    static void sendMsg()
        {
            try
            {
                buffer = Encoding.Default.GetBytes(name);
                acc.Send(buffer);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
    }
    public static void ThreadProc()
    {
        form1.ShowDialog();
    }
    public static void ThreadProc2()
    {
        form2.ShowDialog();
    }
}
}
Form1-要求输入姓名的起始表单,此表单可以被涂鸦,仅用于构建我的基本服务器,最终用于跳棋游戏

public partial class Form1 : Form
{
    Program program;

    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        this.Hide();
        program = new Program();
        program.btnClick(textBox1.Text);
    }
}
Form2用作与我的客户机的Form2类似的界面,基本上有一个标签、文本框和按钮来调用sendMsg()


总而言之,此程序将连接,服务器可以多次向客户端发送数据并更新标签。客户端将第一次向服务器发送数据,然后抛出错误。

您确实意识到您的代码永远不会从这里退出:

public void sendMsg(string s)
{
    bool x = true;
    while (true)
    {
        Thread.Sleep(500);
        if (x == true)
        {
            byte[] msgBuffer = Encoding.ASCII.GetBytes(s);
            sck.Send(msgBuffer);
            x = false;
        }
    }
}
这是一个无限循环,没有中断或返回,也没有出路。那就:

public void sendMsg(string s)
{
    while (true)
    {
        Thread.Sleep(500);
        byte[] msgBuffer = Encoding.ASCII.GetBytes(s);
        sck.Send(msgBuffer);
    }
}

您知道您的代码永远不会从这里退出:

public void sendMsg(string s)
{
    bool x = true;
    while (true)
    {
        Thread.Sleep(500);
        if (x == true)
        {
            byte[] msgBuffer = Encoding.ASCII.GetBytes(s);
            sck.Send(msgBuffer);
            x = false;
        }
    }
}
这是一个无限循环,没有中断或返回,也没有出路。那就:

public void sendMsg(string s)
{
    while (true)
    {
        Thread.Sleep(500);
        byte[] msgBuffer = Encoding.ASCII.GetBytes(s);
        sck.Send(msgBuffer);
    }
}

为什么不使用异步套接字?下面是一些代码:

// Server socket
class ControllerSocket : Socket, IDisposable
{
    // MessageQueue queues messages to be processed by the controller
    public Queue<MessageBase> messageQueue = null;

    // This is a list of all attached clients
    public List<Socket> clients = new List<Socket>();

    #region Events
    // Event definitions handled in the controller
    public delegate void SocketConnectedHandler(Socket socket);
    public event SocketConnectedHandler SocketConnected;

    public delegate void DataRecievedHandler(Socket socket, int bytesRead);
    public event DataRecievedHandler DataRecieved;

    public delegate void DataSentHandler(Socket socket, int length);
    public event DataSentHandler DataSent;

    public delegate void SocketDisconnectedHandler();
    public event SocketDisconnectedHandler SocketDisconnected;
    #endregion

    #region Constructor
    public ControllerSocket(int port)
        : base(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
    {
        // Create the message queue
        this.messageQueue = new Queue<MessageBase>();

        // Acquire the host address and port, then bind the server socket
        IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
        IPAddress ipAddress = ipHostInfo.AddressList[0];
        IPEndPoint localEndPoint = new IPEndPoint(ipAddress, port);
        this.Bind(localEndPoint);
    }
    #endregion

    // Starts accepting client connections
    public void StartListening()
    {
        this.Listen(100);
        this.BeginAccept(AcceptCallback, this);
    }

    // Connects to a client
    private void AcceptCallback(IAsyncResult ar)
    {
        Socket listener = (Socket)ar.AsyncState;
        Socket socket = listener.EndAccept(ar);

        try
        {
            // Add the connected client to the list
            clients.Add(socket);

            // Notify any event handlers
            if (SocketConnected != null)
                SocketConnected(socket);

            // Create an initial state object to hold buffer and socket details
            StateObject state = new StateObject();
            state.workSocket = socket;
            state.BufferSize = 8192;

            // Begin asynchronous read
            socket.BeginReceive(state.Buffer, 0, state.BufferSize, 0,
                ReadCallback, state);
        }
        catch (SocketException)
        {
            HandleClientDisconnect(socket);
        }
        finally
        {
            // Listen for more client connections
            StartListening();
        }
    }

    // Read data from the client
    private void ReadCallback(IAsyncResult ar)
    {
        StateObject state = (StateObject)ar.AsyncState;
        Socket socket = state.workSocket;

        try
        {
            if (socket.Connected)
            {
                // Read the socket
                int bytesRead = socket.EndReceive(ar);

                // Deserialize objects
                foreach (MessageBase msg in MessageBase.Receive(socket, bytesRead, state))
                {
                    // Add objects to the message queue
                    lock (this.messageQueue)
                        messageQueue.Enqueue(msg);
                }

                // Notify any event handlers
                if (DataRecieved != null)
                    DataRecieved(socket, bytesRead);

                // Asynchronously read more client data
                socket.BeginReceive(state.Buffer, state.readOffset, state.BufferSize - state.readOffset, 0,
                    ReadCallback, state);
            }
            else
            {
                HandleClientDisconnect(socket);
            }
        }
        catch (SocketException)
        {
            HandleClientDisconnect(socket);
        }
    }

    // Send data to a specific client
    public void Send(Socket socket, MessageBase msg)
    {
        try
        {
            // Serialize the message
            byte[] bytes = msg.Serialize();

            if (socket.Connected)
            {
                // Send the message
                socket.BeginSend(bytes, 0, bytes.Length, 0, SendCallback, socket);
            }
            else
            {
                HandleClientDisconnect(socket);
            }
        }
        catch (SocketException)
        {
            HandleClientDisconnect(socket);
        }
    }

    // Broadcast data to all clients
    public void Broadcast(MessageBase msg)
    {
        try
        {
            // Serialize the message
            byte[] bytes = msg.Serialize();

            // Process all clients
            foreach (Socket client in clients)
            {
                try
                {
                    // Send the message
                    if (client.Connected)
                    {
                        client.BeginSend(bytes, 0, bytes.Length, 0, SendCallback, client);
                    }
                    else
                    {
                        HandleClientDisconnect(client);
                    }
                }
                catch (SocketException)
                {
                    HandleClientDisconnect(client);
                }
            }
        }
        catch (Exception e)
        {
            // Serialization error
            Console.WriteLine(e.ToString());
        }
    }

    // Data sent to a client socket
    private void SendCallback(IAsyncResult ar)
    {
        try
        {
            Socket socket = (Socket)ar.AsyncState;

            if (socket.Connected)
            {
                // Complete sending the data
                int bytesSent = socket.EndSend(ar);

                // Notify any attached handlers
                if (DataSent != null)
                    DataSent(socket, bytesSent);
            }
            else
            {
                HandleClientDisconnect(socket);
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }

    private void HandleClientDisconnect(Socket client)
    {
        // Client socket may have shutdown unexpectedly
        if (client.Connected)
            client.Shutdown(SocketShutdown.Both);

        // Close the socket and remove it from the list
        client.Close();
        clients.Remove(client);

        // Notify any event handlers
        if (SocketDisconnected != null)
            SocketDisconnected();
    }

    // Close all client connections
    public void Dispose()
    {
        foreach (Socket client in clients)
        {
            if (client.Connected)
                client.Shutdown(SocketShutdown.Receive);

            client.Close();
        }
    }
}

// Client socket

        class ReceiverSocket : Socket
        {
            // MessageQueue queues messages to be processed by the controller
            public Queue<MessageBase> messageQueue = null;

            #region Events
            // Event definitions handled in the controller
            public delegate void SocketConnectedHandler(Socket socket);
            public event SocketConnectedHandler SocketConnected;

            public delegate void DataRecievedHandler(Socket socket, MessageBase msg);
            public event DataRecievedHandler DataRecieved;

            public delegate void DataSentHandler(Socket socket, int length);
            public event DataSentHandler DataSent;

            public delegate void SocketDisconnectedHandler();
            public event SocketDisconnectedHandler SocketDisconnected;

            private IPEndPoint remoteEP = null;
            #endregion

            #region Constructor
            public ReceiverSocket(int port)
                : base(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
            {
                // Create the message queue
                messageQueue = new Queue<MessageBase>();

                // Acquire the host address and port
                IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
                IPAddress ipAddress = ipHostInfo.AddressList[0];
                remoteEP = new IPEndPoint(ipAddress, port);
            }
            #endregion

            // Connect to the server
            public void Connect()
            {
                this.BeginConnect(remoteEP, ConnectCallback, this);
            }

            // Server connected
            private void ConnectCallback(IAsyncResult ar)
            {
    //            Console.WriteLine("Connect Callback");

                try
                {
                    Socket client = (Socket)ar.AsyncState;
                    if (client.Connected)
                    {
                        client.EndConnect(ar);
    //                    Console.WriteLine("Connect Callback - Connected");

                        // Create an initial state object to hold buffer and socket details
                        StateObject state = new StateObject();
                        state.workSocket = client;
                        state.BufferSize = 8192;

                        // Notify any event handlers
                        if (SocketConnected != null)
                            SocketConnected(client);

                        // Begin asynchronous read
                        client.BeginReceive(state.Buffer, state.readOffset, state.BufferSize - state.readOffset, 0,
                            ReceiveCallback, state);
                    }
                    else
                    {
    //                    Console.WriteLine("Connect Callback - Reconnect");
                        Thread.Sleep(5000);
                        Connect();
                    }
                }
                catch (Exception ex)
                {
                    // Attempt server reconnect
                    Reconnect();
                }
            }

            // Read data from the server
            private void ReceiveCallback(IAsyncResult ar)
            {
                try
                {
                    StateObject state = (StateObject)ar.AsyncState;
                    Socket client = state.workSocket;

                    // Read the socket
                    if (client.Connected)
                    {
                        int bytesRead = client.EndReceive(ar);

                        // Deserialize objects
                        foreach (MessageBase msg in MessageBase.Receive(client, bytesRead, state))
                        {
                            // Add objects to the message queue
                            lock (this.messageQueue)
                                this.messageQueue.Enqueue(msg);
                        }

                        // Notify any event handlers
                        if (DataRecieved != null)
                            DataRecieved(client, null);

                        // Asynchronously read more server data
                        client.BeginReceive(state.Buffer, state.readOffset, state.BufferSize - state.readOffset, 0,
                            ReceiveCallback, state);
                    }
                    else
                    {
                        Reconnect();
                    }
                }
                catch (SocketException)
                {
                    // Attempt server reconnect
                    Reconnect();
                }
            }

            public void Send(MessageBase msg)
            {
                try
                {
                    // Serialize the message
                    byte[] bytes = msg.Serialize();

                    if (this.Connected)
                    {
                        // Send the message
                        this.BeginSend(bytes, 0, bytes.Length, 0, SendCallback, this);
                    }
                    else
                    {
                        Reconnect();
                    }
                }
                catch (SocketException sox)
                {
                    // Attempt server reconnect
                    Reconnect();
                }
                catch (Exception ex)
                {
                    int i = 0;
                }
            }

            private void SendCallback(IAsyncResult ar)
            {
                try
                {
                    Socket client = (Socket)ar.AsyncState;

                    if (client.Connected)
                    {
                        // Complete sending the data
                        int bytesSent = client.EndSend(ar);

                        // Notify any event handlers
                        if (DataSent != null)
                            DataSent(client, bytesSent);
                    }
                    else
                    {
                        Reconnect();
                    }
                }
                catch (SocketException)
                {
                    Reconnect();
                }
            }

            // Attempt to reconnect to the server
            private void Reconnect()
            {
                try
                {
                    // Disconnect the original socket
                    if (this.Connected)
                        this.Disconnect(true);

                    this.Close();

                    // Notify any event handlers
                    if (SocketDisconnected != null)
                        SocketDisconnected();
                }
                catch (Exception e)
                {
    //                Console.WriteLine(e.ToString());
                }
            }
        }

    // Encapsulates information about the socket and data buffer
public class StateObject
{
    public Socket workSocket = null;
    public int readOffset = 0;
    public StringBuilder sb = new StringBuilder();

    private int bufferSize = 0;
    public int BufferSize
    {
        set
        {
            this.bufferSize = value;
            buffer = new byte[this.bufferSize];
        }

        get { return this.bufferSize; }
    }

    private byte[] buffer = null;
    public byte[] Buffer
    {
        get { return this.buffer; }
    }
}
//服务器套接字
类控制器套接字:套接字,IDisposable
{
//MessageQueue将控制器处理的消息排队
公共队列messageQueue=null;
//这是所有连接的客户端的列表
public List clients=new List();
#地区活动
//在控制器中处理的事件定义
公共委托void SocketConnectedHandler(套接字);
公共事件SocketConnectedHandler SocketConnected;
公共委托void datareceivedHandler(套接字,int字节读取);
公共事件数据已接收Handler数据已接收;
公共委托void DataSentHandler(套接字,int-length);
公共事件数据处理程序数据;
公共委托void SocketDisconnectedHandler();
公共事件SocketDisconnectedHandler SocketDisconnected;
#端区
#区域构造函数
公共控制器插座(内部端口)
:base(AddressFamily.InterNetwork、SocketType.Stream、ProtocolType.Tcp)
{
//创建消息队列
this.messageQueue=新队列();
//获取主机地址和端口,然后绑定服务器套接字
IPHostEntry ipHostInfo=Dns.GetHostEntry(Dns.GetHostName());
IPAddress IPAddress=ipHostInfo.AddressList[0];
IPEndPoint localEndPoint=新IPEndPoint(ipAddress,port);
this.Bind(localEndPoint);
}
#端区
//开始接受客户端连接
公营机构
{
这个。听(100);
this.beginacept(AcceptCallback,this);
}
//连接到客户端
私有void AcceptCallback(IAsyncResult ar)
{
套接字侦听器=(套接字)ar.AsyncState;
套接字=listener.EndAccept(ar);
尝试
{
//将连接的客户端添加到列表中
clients.Add(socket);
//通知任何事件处理程序
if(SocketConnected!=null)
插座连接(插座);
//创建初始状态对象以保存缓冲区和套接字详细信息
StateObject状态=新的StateObject();
state.workSocket=套接字;
state.BufferSize=8192;
//开始异步读取
socket.BeginReceive(state.Buffer,0,state.BufferSize,0,
ReadCallback,state);
}
捕获(SocketException)
{
手持客户端断开(插座);
}
最后
{
//侦听更多客户端连接
惊人的倾听();
}
}
//从客户端读取数据
私有void ReadCallback(IAsyncResult ar)
{
StateObject状态=(StateObject)ar.AsyncState;
套接字=state.workSocket;
尝试
{
if(插座连接)
{
//读取套接字
int bytesRead=socket.EndReceive(ar);
//反序列化对象
foreach(MessageBase.Receive中的MessageBase消息(套接字、字节读取、状态))
{
//将对象添加到消息队列
锁定(this.messageQueue)
messageQueue.Enqueue(msg);
}
//通知任何事件处理程序
如果(已接收数据!=null)
接收到的数据(套接字、字节读取);
//异步读取更多客户端数据
socket.BeginReceive(state.Buffer、state.readOffset、state.BufferSize-state.readOffset、0、,
ReadCallback,state);
}
其他的
{
手持客户端断开(插座);
}
}
捕获(SocketException)
{
手持客户端断开(插座);
}
}
//将数据发送到特定的客户端
public void Send(套接字、MessageBase消息)
{
尝试
{
//序列化消息
byte[]bytes=msg.Serialize();
if(插座连接)
{
//发送消息
BeginSend(字节,0,字节.长度,0,SendCallback,套接字);
}
其他的
{
手持客户端断开(插座);
}
}
捕获(SocketException)
{
手持客户端断开(插座);
}
}
using System;
using System.Net.Sockets;
using System.Text;
using System.Net;
using System.Threading;
using System.Windows.Forms;

namespace testServer
{
class Program
{
    static Form1 form1 = new Form1();
    static Form2 form2 = new Form2();
    static byte[] buffer { get; set; }
    static Socket sck, acc;
    static string name;

    public void setName(string s)
    {
        name = s;
        string[] asdf = new string[2];
    }

    static string getIP()
    {
        string hostName = System.Net.Dns.GetHostName();
        IPHostEntry ipEntry = System.Net.Dns.GetHostEntry(hostName);
        IPAddress[] addr = ipEntry.AddressList;
        return addr[addr.Length - 1].ToString();
    }

    static void Main(string[] args)
    {
        if (name == null)
        {
            Thread t = new Thread(ThreadProc);
            t.Start();
        } 
        sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        sck.Bind(new IPEndPoint(0, 8888));
        Console.WriteLine("Your local IP address is: " + getIP());
        Console.WriteLine("Awaiting Connection");
        sck.Listen(100);

        acc = sck.Accept();
        Console.WriteLine(" >> Accept connection from client");
        sendMsg();
        while (acc.Connected)
        {
            Thread.Sleep(500);
            byte[] Buffer = new byte[255];
            int receive = acc.Receive(Buffer, 0, Buffer.Length, 0);
            Array.Resize(ref Buffer, receive);
            form2.SetText(Encoding.Default.GetString(Buffer));
        }
    }
    public void btnClick(string s)
    {
        name = s;
        Console.WriteLine("Name: " + name);
        System.Threading.Thread r = new System.Threading.Thread(new System.Threading.ThreadStart(ThreadProc2));
        r.Start();
    }
    public void sendMSG(string s)
    {
            try
            {
                buffer = Encoding.Default.GetBytes(s);
                acc.Send(buffer);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
    }

    static void sendMsg()
        {
            try
            {
                buffer = Encoding.Default.GetBytes(name);
                acc.Send(buffer);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
    }
    public static void ThreadProc()
    {
        form1.ShowDialog();
    }
    public static void ThreadProc2()
    {
        form2.ShowDialog();
    }
}
}
using System;
using System.Windows.Forms;
using System.Text;
using System.Net.Sockets;
using System.Threading;

namespace testClient100
{
public partial class Form1 : Form
{
    System.Net.Sockets.TcpClient clientSocket = new System.Net.Sockets.TcpClient();
    NetworkStream serverStream = default(NetworkStream);
    string readData = null;
    string ipaddress;

    public Form1()
    {
        InitializeComponent();
    }

    private void getMessage()
    {
        while (true)
        {
            serverStream = clientSocket.GetStream();
            int buffSize = 0;
            byte[] inStream = new byte[10025];
            buffSize = clientSocket.ReceiveBufferSize;
            serverStream.Read(inStream, 0, buffSize);
            string returndata = System.Text.Encoding.ASCII.GetString(inStream);
            readData = "" + returndata;
            msg();
        }
    }

    private void msg()
    {
        if (this.InvokeRequired)
            this.Invoke(new MethodInvoker(msg));
        else
            textBox1.Text = textBox1.Text + Environment.NewLine + " >> " + readData;
    }

    private void button1_Click_1(object sender, EventArgs e)
    {
        byte[] outStream = System.Text.Encoding.ASCII.GetBytes(textBox2.Text);
        serverStream.Write(outStream, 0, outStream.Length);
        serverStream.Flush();
    }

    private void button2_Click_1(object sender, EventArgs e)
    {
        ipaddress = textBox4.Text;
        readData = "Conected to Chat Server ...";
        msg();
        clientSocket.Connect(ipaddress, 8888);
        serverStream = clientSocket.GetStream();

        byte[] outStream = System.Text.Encoding.ASCII.GetBytes(textBox3.Text);
        serverStream.Write(outStream, 0, outStream.Length);
        serverStream.Flush();

        Thread ctThread = new Thread(getMessage);
        ctThread.Start();
    }

}
}