我必须开始与我的应用程序的客户端服务器通信。要开始,我想连接到本地主机。Client_Server两个.cs在一个项目问题
下面的代码:
服务器
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)。 如何在本地主机上使用/运行此类程序?
其实我需要一个良好的起点使用套接字,但大多数的净可用的应用程序或者是比较陈旧以上advanced.I已经对套接字使用Linux的工作,但新的这个环境。 2)。 除此之外的任何好例子?
我已经用Google搜索了很多,但SO是我最后的希望!在CodeProject .The项目正在使用的用户界面,并需要启动一个简单的控制台应用程序。
您需要在一个解决方案中创建两个项目。一个项目应该包含服务器。另一个项目应该包含客户端。 – venerik 2014-12-19 07:26:12
您应该签出WCF服务。我不确定你的程序服务的目的是什么,但是从你的代码看来,它正是你需要的东西,因为它让你通过网络调用方法,并且基本上为你完成所有的工作(不一定)一些配置的价格。我建议你在继续使用目前的方法之前阅读这些内容。 – Phoenix 2014-12-19 07:47:13
我的应用程序在本地网络上共享文件@ Phoenix – Khan 2014-12-19 07:52:57