那位高手帮找找我的“c#通信程序“问题
程序如下:
using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace net_communication_client
{
public partial class chat_client : Form
{
public chat_client()
{
InitializeComponent();
initialize();
}
public bool connected = false;
public IPEndPoint ip_point = null;
public Socket socket = null;
public NetworkStream net_stream = null;
public TextReader reader = null;
public TextWriter writer = null;
public Thread thread1 = null;
public string ip = "10.1.3.86";
public string port ="3001";
private void initialize()
{
bool flag=true ;
ip_point = new IPEndPoint(IPAddress.Parse(ip),int.Parse(port));
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
while (flag)
{
socket.Connect(ip_point);
if (socket.Connected)
{
flag = false;
MessageBox.Show("connect successfully,go on!");
}
}
if (socket.Connected)
{
net_stream = new NetworkStream(socket);
reader = new StreamReader(net_stream);
writer = new StreamWriter(net_stream);
thread1 = new Thread(new ThreadStart(this.ThreadListen));
thread1.Start();
connected = true;
}
}
public void ThreadListen()
{
string tmp;
while (connected)
{
try
{
tmp = reader.ReadLine();
if (tmp.Length != 0)
{
lock (this)
{
record.Text += "He say:" + " " + tmp + "\n";
}
}
}
catch (Exception exception)
{
MessageBox.Show(exception.Message);
}
}
socket.Shutdown(SocketShutdown.Both);
socket.Close();
}
private void send_Click(object sender, EventArgs e)
{
if (connected)
{
lock (this)
{
try
{
record.Text += "I say:" + chat_word.Text + "\n";
writer.WriteLine(chat_word.Text);
writer.Flush();
}
catch
{
MessageBox.Show("connection cut off");
}
}
}
else
{
MessageBox.Show("sorry,not connected with others,cannot communication");
}
chat_word.Text = null;
chat_word.Focus();
}
}
}
红线部分调试时总是提示:
An unhandled exception of type 'System.Net.Sockets.SocketException' occurred in System.dll
Additional information: A socket operation was attempted to an unreachable host