我将使用一段简单的测试程序来实现客户端向服务器发送字符串,然后在服务器程序上显示文本。具体该如何操作呢?
以下是客户端代码:
以下是客户端代码:
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();
}
}