我尝试使局域网聊天应用程序,使用C#中的Send()和Receive()函数来发送和接收消息。但问题是,当消息用户类型到控制台,然后按Enter键键盘,这种内容突然出现在控制台屏幕的WriteLine我的形式出现之前(例如:我的预期是你:你好)简单的TCP聊天应用程序c#
我怎么能删除线“你好”。我希望是:
客户:您好
你:你好
代码服务器:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
namespace SimpleTcpSrvr
{
class Program
{
static void Main(string[] args)
{
Console.OutputEncoding = Encoding.UTF8;
int recv;
byte[] data = new byte[1024];
IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"),9050);
Socket newsock = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
newsock.Bind(ipep);
newsock.Listen(10);
Console.WriteLine("Waiting for a client...");
Socket client = newsock.Accept();
IPEndPoint clientep = (IPEndPoint)client.RemoteEndPoint;
Console.WriteLine("Connected with {0} at port {1}",clientep.Address,clientep.Port);
string welcome = "Welcome to my test server";
data = Encoding.UTF8.GetBytes(welcome);
client.Send(data,data.Length,SocketFlags.None);
string input;
while (true)
{
data = new byte[1024];
recv = client.Receive(data);
if (recv == 0)
break;
Console.WriteLine("Client: "+Encoding.UTF8.GetString(data, 0, recv));
input = Console.ReadLine();
Console.WriteLine("You: " + input);
client.Send(Encoding.UTF8.GetBytes(input));
}
Console.WriteLine("Disconnected from {0}", clientep.Address);
client.Close();
newsock.Close();
Console.ReadLine();
}
}
}
代码客户端:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
namespace SimpleTcpClient
{
class Program
{
static void Main(string[] args)
{
Console.OutputEncoding = Encoding.UTF8;
byte[] data = new byte[1024];
string input, stringData;
IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"),9050);
Socket server = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
try
{
server.Connect(ipep);
}
catch(SocketException e)
{
Console.WriteLine("Unable to connect to server.");
Console.WriteLine(e.ToString());
return;
}
int recv = server.Receive(data);
stringData = Encoding.UTF8.GetString(data, 0, recv);
Console.WriteLine(stringData);
while (true)
{
input = Console.ReadLine();
if (input == "exit")
break;
Console.WriteLine("You: " + input);
server.Send(Encoding.UTF8.GetBytes(input));
data = new byte[1024];
recv = server.Receive(data);
stringData = Encoding.UTF8.GetString(data, 0, recv);
byte[] utf8string = System.Text.Encoding.UTF8.GetBytes(stringData);
Console.WriteLine("Server: "+stringData);
}
Console.WriteLine("Disconnecting from server...");
server.Shutdown(SocketShutdown.Both);
server.Close();
Console.WriteLine("Disconnected!");
Console.ReadLine();
}
}
}
谢谢大家!
不,我不想在输入时隐藏输入。我真正需要的是在按下Enter键后隐藏输出。你真的读过我的问题,但说过吗? –
你需要清楚地表达你的问题 - 你说你的预期输出是:客户:嗨 你:你好没有你们之间的问候 - 所以我给了你一个有效的答案。 – PaulF