我正在編寫一個簡單的測試程序,將字符串從客戶端發送到服務器,然後在服務器程序上顯示文本。我將如何去做這件事。從C客戶端向服務器發送字符串
這是我的客戶端代碼。
using System;
using System.Net;
using System.Net.Sockets;
class client
{
static String hostName = Dns.GetHostName();
public static void Main(String[] args)
{
String test = Console.ReadLine();
IPHostEntry ipEntry = Dns.GetHostByName(hostName);
IPAddress[] addr = ipEntry.AddressList;
//The first one in the array is the ip address of the hostname
IPAddress ipAddress = addr[0];
TcpClient client = new TcpClient();
//First parameter is Hostname or IP, second parameter is port on which server is listening
client.Connect(ipAddress, 8);
client.Close();
}
}
這裏是我的服務器代碼
using System;
using System.Net;
using System.Net.Sockets;
class server
{
static int port = 8;
static String hostName = Dns.GetHostName();
static IPAddress ipAddress;
public static void Main(String[] args)
{
IPHostEntry ipEntry = Dns.GetHostByName(hostName);
//Get a list of possible ip addresses
IPAddress[] addr = ipEntry.AddressList;
//The first one in the array is the ip address of the hostname
ipAddress = addr[0];
TcpListener server = new TcpListener(ipAddress,port);
Console.Write("Listening for Connections on " + hostName + "...\n");
//start listening for connections
server.Start();
//Accept the connection from the client, you are now connected
Socket connection = server.AcceptSocket();
Console.Write("You are now connected to the server\n\n");
int pauseTime = 10000;
System.Threading.Thread.Sleep(pauseTime);
connection.Close();
}
}