///连接 private void button1_Click(object sender, EventArgs e) { string strIp = textBox1.Text.Trim() + @":" + textBox2.Text.Trim(); if (Servers.ContainsKey(strIp)) { textBox3.AppendText(@"已与 " + strIp + @" 连接" + Environment.NewLine); return; } try { socketSend = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPAddress ip = IPAddress.Parse(textBox1.Text.Trim()); socketSend.Connect(ip, Convert.ToInt32(textBox2.Text.Trim())); Servers.Add(strIp, socketSend); socketSend = null; //实例化回调 setCallBack = SetValue; receiveCallBack = SetValue; setCmbCallBack = AddCmbItem; comboBox1.Invoke(setCmbCallBack, strIp); textBox3.Invoke(setCallBack, @"与 " + strIp + @" 连接成功"); button2.Enabled = true; button3.Enabled = true; //开启一个新的线程不停的接收服务器发送消息的线程 threadReceive = new Thread(Receive) { IsBackground = true }; //设置为后台线程 ReceiveThreads.Add(strIp, threadReceive); threadReceive.Start(strIp); } catch (Exception /*ex*/) { //MessageBox.Show(@"连接服务端出错:" + ex, @"出错啦", MessageBoxButtons.OK, MessageBoxIcon.Error); socketSend?.Close(); textBox3.AppendText(@"与 " + strIp + @" 连接失败" + Environment.NewLine); } }
private void Close() { client.Close(); }
private void Window_Closed(object sender, EventArgs e) { socket?.Shutdown(SocketShutdown.Both); socket?.Close(); }
/// <summary> /// Завершение подключения, вывод соответствующего сообщения. /// </summary> private void Shutdown() { client.Shutdown(SocketShutdown.Both); client.Close(); }
private void SendMessageFromSocket(object port) { try { // Буфер для входящих данных byte[] bytes = new byte[1024]; // Соединяемся с удаленным устройством // Устанавливаем удаленную точку для сокета IPHostEntry ipHost = Dns.GetHostEntry("localhost"); IPAddress ipAddr = ipHost.AddressList[0]; IPEndPoint ipEndPoint = new IPEndPoint(ipAddr, (int)port); Socket sender = new Socket(ipAddr.AddressFamily, SocketType.Stream, ProtocolType.Tcp); // Соединяем сокет с удаленной точкой sender.Connect(ipEndPoint); string request = ""; Dispatcher.Invoke(() => { request = indexTextBox.Text; indexTextBox.Text = string.Empty; }); byte[] msg = Encoding.UTF8.GetBytes(request); // Отправляем данные через сокет int bytesSent = sender.Send(msg); // Получаем ответ от сервера int bytesRec = sender.Receive(bytes); string str = Encoding.UTF8.GetString(bytes, 0, bytesRec); for (int i = 0; i < str.Length; i++) { if (str[i] == '.') { str = str.Insert(i + 1, ", "); } } Dispatcher.Invoke(() => { streetTextBox.Text = str; }); // Освобождаем сокет sender.Shutdown(SocketShutdown.Both); sender.Close(); } catch (SocketException ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error); } catch (ArgumentNullException ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error); } }
//Close socket void Close() { client.Close(); }
// Function to get the score of every player from the server public List <Player> GetScoreAllPlayers() { List <Player> players = new List <Player>(); // Data buffer for incoming data. byte[] bytes = new byte[1024]; // Connect to a remote device. try { var address = Dns.GetHostEntry(serverAddress).AddressList.First(ip => ip.AddressFamily == AddressFamily.InterNetworkV6); // IPV4 to IPV6 address IPAddress ipAddress = address; IPEndPoint remoteEP = new IPEndPoint(ipAddress, Int32.Parse(serverPort)); // Create a TCP/IP socket. Socket sender = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp); // Connect the socket to the remote endpoint. Catch any errors. try { sender.Connect(remoteEP); // Encode the data string into a byte array. byte[] msg = Encoding.ASCII.GetBytes("<ScorePlayers>" + this.id);// Ask the score of other players // Send the data through the socket. int bytesSent = sender.Send(msg); // Receive the response from the remote device. int bytesRec = sender.Receive(bytes); string result = Encoding.ASCII.GetString(bytes, 0, bytesRec); if (result.IndexOf("<ReturnScorePlayers>") < 0) { Console.WriteLine("Server return error."); } // Release the socket. sender.Shutdown(SocketShutdown.Both); sender.Close(); // Get the answer of the server and put it on the List of players score result = result.Replace("<ReturnScorePlayers>", ""); string[] result_array = result.Split(';'); for (int i = 0; i < result_array.Length; i += 2) { players.Add(new Player(result_array[i], Int16.Parse(result_array[i + 1])));// Create a new player with its id and score and add it to the list of all players } return(players); } catch (Exception e) { Console.WriteLine("Unexpected exception : {0}", e.ToString()); } } catch (Exception e) { Console.WriteLine(e.ToString()); } return(null); }
/// <summary> /// đóng kết nối hiện thời lại /// </summary> void _Close() { client.Close(); }