using System; using System.Net.Sockets; using System.Net; using System.Text; namespace socket_server { class MainClass { static string ip = "192.168.43.2"; //设置与客户端相应的IP static int port = 1111; //设置与客户端相应的端口号 public static void Main(string[] args) { Console.WriteLine("服务器启动....."); //创建服务端 Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //绑定对应的IP与端口号 EndPoint point = new IPEndPoint(IPAddress.Parse(ip), port); server.Bind(point); server.Listen(100); //设置接收消息 Socket socket = server.Accept(); while (true) { byte[] bytes = new byte[1024]; int len = socket.Receive(bytes); string msg = Encoding.UTF8.GetString(bytes, 0, len); Console.WriteLine(msg); } } } } 如何让message=Console.WriteLine(msg);
时间: 2024-02-10 10:25:11 浏览: 182
要将消息 `msg` 赋值给 `message` 变量,你可以在 `while` 循环内部添加相应的代码行。请参考以下修改后的代码示例:
```csharp
using System;
using System.Net.Sockets;
using System.Net;
using System.Text;
namespace socket_server
{
class MainClass
{
static string ip = "192.168.43.2"; // 设置与客户端相应的IP
static int port = 1111; // 设置与客户端相应的端口号
public static void Main(string[] args)
{
Console.WriteLine("服务器启动.....");
// 创建服务端
Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// 绑定对应的IP与端口号
EndPoint point = new IPEndPoint(IPAddress.Parse(ip), port);
server.Bind(point);
server.Listen(100);
// 设置接收消息
Socket socket = server.Accept();
while (true)
{
byte[] bytes = new byte[1024];
int len = socket.Receive(bytes);
string msg = Encoding.UTF8.GetString(bytes, 0, len);
Console.WriteLine(msg);
string message = msg; // 将消息赋值给变量message
Console.WriteLine("message: " + message); // 输出变量message
}
}
}
}
```
在修改后的代码中,我添加了一行 `string message = msg;` 来将 `msg` 的值赋给 `message` 变量。然后,我使用 `Console.WriteLine` 打印出变量 `message` 的值。
阅读全文