private void ReceiveData(object obj)
{
//User类封装了TcpClient,StreamReader和StreamWriter
User user = (User)obj;
TcpClient client = user.client;
string receiveString = null;
receiveString = sr.ReadLine();
service.SetListBox(string.Format("来自{0}:{1}", user.userName, receiveString));
string[] splitString = receiveString.Split(',');
switch (splitString[0])
{
case "Login":
user.userName = string.Format("[{0}--{1}]", splitString[1], client.Client.RemoteEndPoint);
service.SendToOne(user, "Welcome");
break;
default:
break;
}
}
class Service
{
private ListBox listbox;
private delegate void SetListBoxCallback(string str);
private SetListBoxCallback setListBoxCallback;
public Service(ListBox listbox)
{
this.listbox = listbox;
setListBoxCallback = new SetListBoxCallback(SetListBox);
}
public void SetListBox(string str)
{
if (listbox.InvokeRequired)
{
listbox.Invoke(setListBoxCallback, str);
}
else
{
listbox.Items.Add(str);
listbox.SelectedIndex = listbox.Items.Count - 1;
listbox.ClearSelected();
}
}
public void SendToOne(User user, string str)
{
try
{
user.sw.WriteLine(str);
user.sw.Flush();
SetListBox(string.Format("向{0}发送{1}", user.userName, str));
}
catch
{
SetListBox(string.Format("向{0}发送信息失败", user.userName));
}
}
}