考虑以下代码:
<?php
function absolute_url($page = 'Index.php')
{
//header('Location: http:\\localhost');
//exit(); //terminates the script
$url = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']);
$url = rtrim($url, '/\\');
$url .= '/' . $page;
return $url;
}
function checkLogin($Email = '', $password = '')
{
$errors = array();
if(empty($Email))
$errors[] = 'You must enter a Email';
if(empty($password))
$errors[] = 'You must enter a password';
if(empty($errors))
{
////set up database econnection
include 'DBConn.php';
$db = new DBConn();
$dbc = $db->getDBConnection();
$q = "select Email, FName, LName from Users_1 where Email = '$Email' and Password = '$password'";
$r = mysqli_query($dbc, $q);
if($r)
{
if(mysqli_affected_rows($dbc) != 0)
{
$row = mysqli_fetch_array($r, MYSQLI_ASSOC);
return array(true, $row);
}
else
{
$errors[] = 'Passwords do not match';
}
}
else{
echo '<p class="error"> Oh dear. There was a database error</p>';
echo '<p class = "error">' . mysqli_error($dbc) .'</p>';
}
}
return array(false, $errors);
}
?>
此程序将两个客户端连接作为不同的线程接受,并在每个线程的处理程序类中运行class program
{
public static ConcurrentDictionary<string, int> dictionary = new ConcurrentDictionary<string,int>();
static void Main(string[] args)
{
runServer();
}
static void runServer()
{
//Server setup
Handler threadRequest;
Thread[] threadsArray = new Thread[2];
int i = 0;
while(true)
{
Socket connection;
connection = listener.AcceptSocket();
threadRequest = new Hander();
threadsArray[i] = new Thread(() => threadRequest.clientInteraction(connection, dictionary));
threadsArray[i].Start();
i++;
}
}
}
class Handler
{
public void clientInteraction(Socket connection, ConcurrentDictionary<string, int> dictionary)
{
NetworkStream socketStream;
socketStream = new NetworkStream(connection);
StreamWriter sw = new StreamWriter(socketStream);
StreamReader sr = new StreamReader(socketStream);
parseStrings(out pTeamName); //checks to see if its a valid "add team" request
dictionary.tryAdd(pTeamName, 0);
while(dictionary.Count < 2)
{
//hang until two teams
}
sw.WriteLine("Welcome To The Game.");
sw.Flush();
foreach(KeyValuePair<string, int> kvp in dictionary)
{
Console.WriteLine("Team: {0}", kvp.Key);
}
foreach(KeyValuePair<string, int> kvp in dictionary)
{
sw.WriteLine("Team: {0}", kvp.Key);
sw.Flush();
}
}
}
方法。我担心的是,如果两个线程同时命中clientInteraction
,服务器将无法执行它。
我推断这是因为服务器没有打印&#34;欢迎来到游戏&#34;到任一客户端,只打印一个sw.Flush()
(同一条目)的条目到两个客户端,省略一个。
从调试和dictionary
到服务器控制台,我知道字典已正确填充。我很困惑为什么给客户的写作不起作用。
欢迎任何帮助,如果我遗漏任何重要内容,请告知我们。提前谢谢。
编辑:无论出于何种原因,似乎每个人都有其他的&#39;一套冲洗工作。例如我放了:Console.WriteLine
在foreach循环下方将字典打印到客户端。前两个 while(true)
{
sw.WriteLine("BOO");
sw.Flush();
Console.ReadKey();
}
打印&#34; BOO&#34;到其中一个客户端(取决于哪个线程是第一个),然后两个客户端什么都不做。接下来的两个打印&#34; BOO&#34;再次。我并不特别希望使用i = 2 ReadKeys
循环对每个sw.Flush()
进行框架化,以使其正常工作。
答案 0 :(得分:0)
确保没有任何单独的连接同时执行操作不是您的责任。您需要确保不同时使用/访问来自多个线程的单个连接,但操作系统有责任确保不同连接的操作不会相互影响