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

Socket single client/server connection, server can send multiple times, client can only once(Socket单客户端/服务器连接,服务器可以发送多次,客户端只能发送一次)

本文介绍了Socket单客户端/服务器连接,服务器可以发送多次,客户端只能发送一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have written a client and server application that I need to use to connect a checkers game I made in C#. I have got the client and server to connect and the server can repeatedly send the client messages to update a label but when the client tries to send a message it throws the error

发送或接收数据的请求被拒绝,因为套接字未连接并且(当使用 sendto 调用在数据报套接字上发送时)没有提供地址."

"A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a sendto call) no address was supplied."

到目前为止,这是我的客户端和服务器.

Here is my client and server so far.

客户 -

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;
            /

本文标题为:Socket单客户端/服务器连接,服务器可以发送多次,客户端只能发送一次

基础教程推荐