我必须开始使用我的应用程序的客户端服务器通信。首先,我想连接到本地主机。
以下是代码:
服务器
public class serv
{
public static void Main()
{
try
{
IPAddress ipAd = IPAddress.Parse("127.0.0.1"); //use local m/c IP address, and use the same in the client
/* Initializes the Listener */
TcpListener myList=new TcpListener(ipAd,1025);
/* Start Listeneting at the specified port */
myList.Start();
Console.WriteLine("The server is running at port 1025...");
Console.WriteLine("The local End point is :" + myList.LocalEndpoint );
Console.WriteLine("Waiting for a connection.....");
Socket s=myList.AcceptSocket();
Console.WriteLine("Connection accepted from "+s.RemoteEndPoint);
byte[] b=new byte[100];
int k=s.Receive(b);
Console.WriteLine("Recieved...");
for (int i=0;i<k;i++)
Console.Write(Convert.ToChar(b[i]));
ASCIIEncoding asen=new ASCIIEncoding();
s.Send(asen.GetBytes("The string was recieved by the server."));
Console.WriteLine("\nSent Acknowledgement");
/* clean up */
s.Close();
myList.Stop();
Console.ReadKey();
}
catch (Exception e)
{
Console.WriteLine("Error..... " + e.StackTrace);
}
}
}
客户端
public class clnt
{
public static void Main()
{
try
{
TcpClient tcpclnt = new TcpClient();
Console.WriteLine("Connecting.....");
tcpclnt.Connect("127.0.0.1",1025); // use the ipaddress as in the server program
Console.WriteLine("Connected");
Console.Write("Enter the string to be transmitted : ");
String str=Console.ReadLine();
Stream stm = tcpclnt.GetStream();
ASCIIEncoding asen= new ASCIIEncoding();
byte[] ba=asen.GetBytes(str);
Console.WriteLine("Transmitting.....");
stm.Write(ba,0,ba.Length);
byte[] bb=new byte[100];
int k=stm.Read(bb,0,100);
for (int i=0;i<k;i++)
Console.Write(Convert.ToChar(bb[i]));
tcpclnt.Close();
Console.ReadKey();
}
catch (Exception e)
{
Console.WriteLine("Error..... " + e.StackTrace);
}
}
}
该项目有两个Main()
功能。因此,为避免冲突,我将serv.cs
设置为StartupObject
,但导致无法访问客户端的控制台窗口以发送消息。
1)。如何在本地主机上使用/运行此类程序?
我实际上需要一个很好的起点来使用套接字,但网上提供的大多数应用程序都已经过时或者更高级。我已经使用 Linux 处理了套接字但是对这个环境不熟悉。
2)。除此之外还有什么好的例子吗?
我已经搜索了很多但是SO是我最后的希望!.CodeProject上的项目正在使用UI,启动时需要一个简单的控制台应用程序。
答案 0 :(得分:1)
不需要您的代码。 你开始这两个项目吗? 您必须先启动服务器,然后启动客户端,以便客户端可以连接到等待的服务器。