如何通过套接字发送多条消息

时间:2016-04-08 15:13:15

标签: c# sockets

我在互联网上看到如何用C#创建套接字服务器,
在向服务器发送一条消息后,服务器关闭 我一直想知道如何更改它以便它可以处理多条消息。

代码:

static void startServer() {
    Console.WriteLine("[*] Opening server...");
    TcpListener listener = new TcpListener(IPAddress.Any, 45784);
    listener.Start();
    Console.WriteLine("[*] Server waiting on port " + 45784);
    TcpClient client = listener.AcceptTcpClient();
    Console.WriteLine("Client connected!");

    StreamReader STR = new StreamReader(client.GetStream());
    Console.WriteLine(STR.ReadLine());
}
static void Main(string[] args)
    {
        string ip = GetIpAdress();
        Console.WriteLine("server on: " + ip);
        startServer();
        Console.Read();
    }

3 个答案:

答案 0 :(得分:0)

我相信这是非常基本的。只需将您的代码只读一条消息并退出即可。

要阅读多条消息,您只需在此行周围放置一个while循环。

Console.WriteLine(STR.ReadLine());

答案 1 :(得分:0)

您的服务器在收到一条消息后就停止了,因为这是您告诉它要做的所有事情(到目前为止)。

这些行:

StreamReader STR = new StreamReader(client.GetStream());
Console.WriteLine(STR.ReadLine());

将处理来自客户端的一条消息,然后停止,因为您没有告诉它抓取另一条消息。

如果您希望服务器监听并处理任意数量的消息,您需要将此代码放在循环中。

试试这个:

static TcpListener StartServer()
{
    Console.WriteLine("[*] Opening server...");
    TcpListener listener = new TcpListener(IPAddress.Any, 45784);
    listener.Start();
    Console.WriteLine("[*] Server waiting on port " + 45784);

    return listener;
}

static void Listen(CancellationToken cancellationToken)
{
    string ip = GetIpAddress();
    Console.WriteLine("server on: ");
    var listener = StartServer();

    var client = listener.AcceptTcpClient();
    Console.WriteLine("Client connected!");

    var reader = new StreamReader(client.GetStream());

    while (!cancellationToken.IsCancellationRequested)
    {
        Console.WriteLine(reader.ReadLine());
    }
}

static void Main(string[] args)
{
    var cancellationSource = new CancellationTokenSource();

    Console.CancelKeyPress += (s, e) =>
    {
        e.Cancel = true;
        cancellationSource.Cancel();
    };

    Listen(cancellationSource.Token);
}

此代码将继续从远程客户端获取行,直到使用 Ctrl - C 取消服务器。它使用CancellationToken挂钩取消事件,但如果你愿意,也可以使用bool标志。

警告:这只接受来自单个客户端的消息,而不是来自多个客户端的消息(这是一个不同的挑战)。此外,一旦发送了取消事件,服务器在退出和关闭连接之前会等待来自客户端的另一条消息,因为ReadLine()会阻塞该线程,直到它看到一条消息进入。

答案 2 :(得分:0)

  

我的意思是,多个消息,一个接一个地从一个客户端发送。

您需要添加一些循环。

protected void createDialog() {
        final Dialog dialog = new Dialog(WeightActivity.this, android.R.style.Theme_Material_Light_Dialog_Alert);
        dialog.getWindow();
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(R.layout.dialog_add_weight);

        Button okButton = (Button) dialog.findViewById(R.id.okButton);
        final ImageButton selectImageButton = (ImageButton) dialog.findViewById(R.id.selectImageButton);
        final ImageView imageView = (ImageView) dialog.findViewById(R.id.imageView);

        selectImageButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            get_permissions();
            selectImage();
            imageView.setImageBitmap(bm);
            }
        });

        dialog.show();
    }

private void selectImage() {
    final String[] items = WeightActivity.this.getResources().getStringArray(R.array.photo_options);
    AlertDialog.Builder builder = new AlertDialog.Builder(WeightActivity.this);
    builder.setTitle(R.string.weight_dialog_add_photo);
    builder.setItems(items, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int item) {
            if (items[item].equals(items[0])) {
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(intent, REQUEST_CAMERA);
            } else if (items[item].equals(items[1])) {
                Intent intent = new Intent(
                        Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                intent.setType("image/*");
                startActivityForResult(
                        Intent.createChooser(intent, "Select File"),
                        SELECT_FILE);
            }
        }
    });
    builder.show();
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK) {
        if (requestCode == REQUEST_CAMERA) {
            bm = (Bitmap) data.getExtras().get("data");
        } else if (requestCode == SELECT_FILE) {
            Uri selectedImageUri = data.getData();
            String[] projection = {MediaStore.MediaColumns.DATA};
            CursorLoader cursorLoader = new CursorLoader(this, selectedImageUri, projection, null, null,
                    null);
            Cursor cursor = cursorLoader.loadInBackground();
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
            cursor.moveToFirst();
            String selectedImagePath = cursor.getString(column_index);
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(selectedImagePath, options);
            options.inJustDecodeBounds = false;
            bm = BitmapFactory.decodeFile(selectedImagePath, options);
        }
    }
}