作为一个侧面项目,我正在进行回合制游戏。我的计划是简单地从一个玩家发送一个字符串到另一个玩家,描述之前采取的行动。 IE" Bob,MoveX,5,MoveY,3,END;"
我有一个简单的程序来回发送字符串,但它要求每一方交替发送,这对我来说不会起作用。这是2个文件。
服务器:
using System;
using System.Net;
using System.Net.Sockets;
using System.IO;
public class ServerSocket1
{
public static void Main()
{
try
{
bool status = true;
string servermessage = "";
string clientmessage = "";
IPAddress localAddr = IPAddress.Parse("127.0.0.1");
TcpListener tcpListener = new TcpListener(localAddr, 8100);
tcpListener.Start();
Console.WriteLine("Server Started");
Socket socketForClient = tcpListener.AcceptSocket();
Console.WriteLine("Client Connected");
NetworkStream networkStream = new NetworkStream(socketForClient);
StreamWriter streamwriter = new StreamWriter(networkStream);
StreamReader streamreader = new StreamReader(networkStream);
while (status)
{
if (socketForClient.Connected)
{
servermessage = streamreader.ReadLine();
Console.WriteLine("Client:" + servermessage);
if ((servermessage == "bye"))
{
status = false;
streamreader.Close();
networkStream.Close();
streamwriter.Close();
return;
}
Console.Write("Server:");
clientmessage = Console.ReadLine();
streamwriter.WriteLine(clientmessage);
streamwriter.Flush();
}
}
streamreader.Close();
networkStream.Close();
streamwriter.Close();
socketForClient.Close();
Console.WriteLine("Exiting");
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
客户:
using System;
using System.Net.Sockets;
using System.IO;
public class ClientSocket1
{
static void Main(string[] args)
{
TcpClient socketForServer;
bool status = true;
try
{
socketForServer = new TcpClient("localhost", 8100);
Console.WriteLine("Connected to Server");
}
catch
{
Console.WriteLine("Failed to Connect to server{0}:999", "localhost");
return;
}
NetworkStream networkStream = socketForServer.GetStream();
StreamReader streamreader = new StreamReader(networkStream);
StreamWriter streamwriter = new StreamWriter(networkStream);
try
{
string clientmessage = "";
string servermessage = "";
while (status)
{
Console.Write("Client:");
clientmessage = Console.ReadLine();
if ((clientmessage == "bye") || (clientmessage == "BYE"))
{
status = false;
streamwriter.WriteLine("bye");
streamwriter.Flush();
}
if ((clientmessage != "bye") && (clientmessage != "BYE"))
{
streamwriter.WriteLine(clientmessage);
streamwriter.Flush();
servermessage = streamreader.ReadLine();
Console.WriteLine("Server:" + servermessage);
}
}
}
catch
{
Console.WriteLine("Exception reading from the server");
}
streamreader.Close();
networkStream.Close();
streamwriter.Close();
}
}
我计划添加大量功能,但我想弄清楚为什么我需要替换谁发送。
注意:游戏只支持2个玩家,所以我可以放心地假设有一个主机(服务器)和一个客户端。