我必須開始與我的應用程序的客戶端服務器通信。要開始,我想連接到本地主機。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