C# 通过网络流(套接字)写入/读取聊天字符串
抱歉,如果这很难理解,请第一次尝试C# 我试图在连接到服务器的客户端之间进行简单的公开“聊天”。我曾尝试将整数传递到服务器并打印出来,一切都很好,但是,当我切换到字符串时,它似乎只能传递1个字符(因为C# 通过网络流(套接字)写入/读取聊天字符串,c#,string,sockets,chat,networkstream,C#,String,Sockets,Chat,Networkstream,抱歉,如果这很难理解,请第一次尝试C# 我试图在连接到服务器的客户端之间进行简单的公开“聊天”。我曾尝试将整数传递到服务器并打印出来,一切都很好,但是,当我切换到字符串时,它似乎只能传递1个字符(因为ns.Write(已转换,0,1);)。如果我将ns.Write增加到ns.Write(已转换,0,10)当我输入少于10个字符的消息时,一切都会崩溃(客户端和服务器) 服务器代码: using System; using System.Collections.Generic; using Syst
ns.Write(已转换,0,1);
)。如果我将ns.Write增加到ns.Write(已转换,0,10)
当我输入少于10个字符的消息时,一切都会崩溃(客户端和服务器)
服务器代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Net.Sockets;
namespace MultiServeris
{
class Multiserveris
{
static void Main(string[] args)
{
TcpListener ServerSocket = new TcpListener(1000);
ServerSocket.Start();
Console.WriteLine("Server started");
while (true)
{
TcpClient clientSocket = ServerSocket.AcceptTcpClient();
handleClient client = new handleClient();
client.startClient(clientSocket);
}
}
}
public class handleClient
{
TcpClient clientSocket;
public void startClient(TcpClient inClientSocket)
{
this.clientSocket = inClientSocket;
Thread ctThread = new Thread(Chat);
ctThread.Start();
}
private void Chat()
{
byte[] buffer = new byte[10];
while (true)
{
NetworkStream ns = clientSocket.GetStream();
ns.Read(buffer,0,1);
string line = Encoding.UTF8.GetString(buffer);
Console.WriteLine(line);
}
}
}
}
客户端代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
namespace Klientas
{
class Klientas
{
static void Main(string[] args)
{
while (true)
{
TcpClient clientSocket = new TcpClient("localhost", 1000);
NetworkStream ns = clientSocket.GetStream();
byte[] buffer = new byte[10];
string str = Console.ReadLine();
byte[] converted = System.Text.Encoding.UTF8.GetBytes(str);
ns.Write(converted, 0, 1);
}
}
}
}
最好使用BinaryReader/BinaryWriter类来正确格式化和读取数据。这样就不需要自己处理了。例如,在客户端中,请执行以下操作:
BinaryWriter writer = new BinaryWriter(clientSocket.GetStream());
writer.Write(str);
在服务器中:
BinaryReader reader = new BinaryReader(clientSocket.GetStream());
Console.WriteLine(reader.ReadString());
在同一流上使用BinaryReader或BinaryWriter时,如果您的.NET framework版本为4.5或更高版本,请确保使用重载使基础流保持打开状态:
using (var w = new BinaryWriter(stream, Encoding.UTF8, true)) {}
从流中读取时的一个常见错误是没有检查Read方法返回的内容。(它可能与您要读取的大小不匹配)L.B,如果我同时将写入和读取更改为(例如,(已转换,0,10),它将崩溃。@user43132我已经读取了它。但你似乎没有仔细阅读我的评论。是的,我刚刚意识到你在说什么。如果我输入10个字符以上的信息,一切正常。是否有办法使读/写不依赖于write()和read()size参数?
var reader=new StreamReader(ns);var line=reader.ReadLine()代码>?太棒了!它立刻起作用了!在客户端打印流时也使用它有意义吗?仅为线程使用服务器?BinaryWrite和BinaryReader需要位于两端才能正常工作。