主界面的设计
<Window x:Class="SocketClient.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:SocketClient"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525" ShowInTaskbar="False" IsHitTestVisible="True">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="9*"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
</Grid.RowDefinitions>
<RichTextBox Name="tb_receive" Grid.Row="0" Background="Black" Foreground="White" FontSize="20"></RichTextBox>
<TextBox Name="tb_send" Grid.Row="1" VerticalAlignment="Center" FontSize="18"></TextBox>
</Grid>
</Window>
主界面的实现
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Diagnostics;
namespace SocketClient
{
public partial class MainWindow : Window
{
private SocketManager socketMgr = null;
public MainWindow()
{
InitializeComponent();
tb_send.KeyUp += new KeyEventHandler(TextBox_KeyUp);
socketMgr = new SocketManager(this);
socketMgr.Connect("172.16.3.230", 1234);
}
private void Btn_Click(object sender, RoutedEventArgs e)
{
Button btn = sender as Button;
switch(btn.Name)
{
case "btn_send":
socketMgr.Send(tb_send.Text);
break;
}
}
public void ReceiveData(string str)
{
Action receiveDelegate = delegate ()
{
str += "\r";
tb_receive.AppendText(str);
};
this.Dispatcher.BeginInvoke(receiveDelegate);
}
private void TextBox_KeyUp(object sender, KeyEventArgs e)
{
switch(e.Key)
{
case Key.Enter:
socketMgr.Send(tb_send.Text);
tb_send.Text = "";
break;
}
}
protected override void OnClosed(EventArgs e)
{
Debug.WriteLine("closed....\n\n");
if (socketMgr!=null)
{
socketMgr.Close();
}
}
}
}
SocketManager的实现
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Windows;
namespace SocketClient
{
public class SocketManager
{
private bool isConnected = false;
private bool isClosed = false;
private Socket clientSocket=null;
MainWindow win = null;
private byte[] receive_buffer = new byte[2048];
public SocketManager(MainWindow window)
{
win = window;
}
public void Connect(string ip,int port)
{
Thread reconnectThread = new Thread(ReconnectFunction);
IPAddress ipAddr = IPAddress.Parse(ip);
IPEndPoint ipEndPoint = new IPEndPoint(ipAddr, port);
reconnectThread.Start((object)ipEndPoint);
Thread receiveThread = new Thread(ReceiveFunction);
receiveThread.Start();
Thread jumpHeartThread = new Thread(JumpHeartFunction);
jumpHeartThread.Start();
}
private void JumpHeartFunction()
{
while(true)
{
if (isClosed)
{
break;
}
if (isConnected)
{
try
{
Send("1");
Thread.Sleep(5000);
}
catch (Exception e)
{
Debug.WriteLine("Exception:{0}\n", e);
isConnected = false;
}
}
}
}
private void ReceiveFunction()
{
while(true)
{
if(isClosed)
{
break;
}
if(isConnected)
{
try
{
int len = clientSocket.Receive(receive_buffer);
if(len==0)
{
isConnected = false;
continue;
}
string receive_str = Encoding.GetEncoding("GBK")
.GetString(receive_buffer, 0, len);
if (win!=null)
{
win.ReceiveData(receive_str);
}
Debug.WriteLine("Receive:{0}\n\n", receive_str);
}
catch(Exception e)
{
Debug.WriteLine("Exception:{0}\n",e);
isConnected = false;
}
}
}
}
public void Close()
{
clientSocket.Shutdown(SocketShutdown.Both);
clientSocket.Close();
isClosed = true;
isConnected = false;
}
public void Send(byte[] byte_msg)
{
try
{
clientSocket.Send(byte_msg);
}
catch(Exception e)
{
Debug.WriteLine("Exception...{0}",e);
isConnected = false;
}
}
public void Send(string string_msg)
{
try
{
byte[] sendBytes = Encoding.GetEncoding("GBK").GetBytes(string_msg);
clientSocket.Send(sendBytes);
}
catch (Exception e)
{
Debug.WriteLine("Exception...{0}", e);
isConnected = false;
}
}
private void ReconnectFunction(object parameter)
{
IPEndPoint ipEndPoint = (IPEndPoint)parameter;
while (true)
{
if(isClosed)
{
break;
}
if(!isConnected)
{
try
{
clientSocket = new Socket(AddressFamily.InterNetwork,
SocketType.Stream,ProtocolType.Tcp);
clientSocket.Connect(ipEndPoint);
isConnected = true;
}
catch (Exception e)
{
Debug.WriteLine("Exception:{0}", e);
isConnected = false;
clientSocket = null;
}
}
Thread.Sleep(1000);
}
}
}
}