C# 如何使用任何internet协议发送简单字符串
我试图创建一个程序,通过互联网发送和接收字符串。我的问题是,我找到了太多的方法来建立联系,而我和我的朋友尝试过的事情从来没有完全奏效 这是我认为最适合我的情况的代码: 它使用TCP,在创建对象时首先测试连接。之后,可以随时执行C# 如何使用任何internet协议发送简单字符串,c#,sockets,C#,Sockets,我试图创建一个程序,通过互联网发送和接收字符串。我的问题是,我找到了太多的方法来建立联系,而我和我的朋友尝试过的事情从来没有完全奏效 这是我认为最适合我的情况的代码: 它使用TCP,在创建对象时首先测试连接。之后,可以随时执行Send()和Receive(),这是此类的目标。 此时,它在TestConnection()中的socket.Connect(endPoint)处出现错误,错误为System.Net.Internals.SocketExceptionFactory+extendedsso
Send()
和Receive()
,这是此类的目标。
此时,它在TestConnection()
中的socket.Connect(endPoint)
处出现错误,错误为System.Net.Internals.SocketExceptionFactory+extendedssocketexception(10060)
:
这个问题不是由端口转发(如果我错了,请纠正我)引起的,因为我们现在在本地测试它:我们使用执行测试的主机的IP创建一个套接字
我们的具体问题是:这通常是发送字符串的正确方式吗?为什么这段代码会引发异常?
另外,如果有人有空闲时间:你如何在能够发送信息的同时收听/接收信息?我假设这在控制台中是不可能的,因为ReadLine()会暂停所有操作,但是您能同时运行两个线程吗
如果有人能引导我们朝着正确的方向前进,这将对我们意义重大
非常感谢,
塞拉斯
public class DataTransfer
{
public Socket socket;
public IPAddress ipAdd;
public IPEndPoint endPoint;
/// <summary>
/// This class holds everything to create and manage a connection with one other client
/// </summary>
/// <param name="ip">The IP from the receiver</param>
/// <param name="port">The port used to contact the receiver</param>
public DataTransfer(string ip, int port)
{
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
ipAdd = IPAddress.Parse(ip);
endPoint = new IPEndPoint(ipAdd, port);
} // constructor
/// <summary>
/// Opens the connection and executes a Send() and Receive() for testing purposes
/// </summary>
/// <returns>true when succesful, false when any exception occured</returns>
/// <remarks>Should be executed after creating this object</remarks>
public bool TestConnection()
{
try
{
socket.Connect(endPoint); //is never closed yet... is this needed?
Send("Alpha Beta Charlie");
Receive();
}
catch (Exception e)
{
Console.WriteLine("Connection failed... Could not connect to " + endPoint.ToString());
Console.WriteLine("Error: " + e);
return false;
}
return true;
}
public string Receive()
{
try
{
byte[] buffer = new byte[1024];
int msgLength = socket.Receive(buffer);
string returnData = Encoding.ASCII.GetString(buffer, 0, msgLength);
return $"Message received: {returnData} from {socket.RemoteEndPoint}";
}
catch (Exception e)
{
Console.WriteLine("Could not receive message: " + e);
return null;
}
}
public bool Send(string msg)
{
try
{
byte[] byData = Encoding.ASCII.GetBytes(msg);
socket.Send(byData);
return true;
}
catch (Exception e)
{
Console.WriteLine("Could not send message: " + e);
return false;
}
}
}
static void ConnectUser(string IP)
{
IP = "Haha no this is censored"; //overwrites for testing purposes
DataTransfer connection = new DataTransfer(IP, 445);
if (!connection.TestConnection()) return;
//and now use the connection:
connection.Send("Hello World!");
string msgReceived = connection.Receive();
if (msgReceived != null) Console.WriteLine("Message received!: " + msgReceived);
//irrelevant code here
}