Socket通信基础
来源:互联网 发布:java求二叉树的高度 编辑:程序博客网 时间:2024/05/01 20:53
Socket通信传递数据
服务端:
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
Thread mythread ;
Socket socket;
// 清理所有正在使用的资源。
protected override void Dispose( bool disposing )
{
try
{
socket.Close();//释放资源
mythread.Abort ( ) ;//中止线程
}
catch{ }
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
public static IPAddress GetServerIP()
{
IPHostEntry ieh=Dns.GetHostByName(Dns.GetHostName());
return ieh.AddressList[0];
}
private void BeginListen()
{
IPAddress ServerIp=GetServerIP();
IPEndPoint iep=new IPEndPoint(ServerIp,8000);
socket=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
byte[] byteMessage=new byte[100];
this.label1.Text=iep.ToString();
socket.Bind(iep);
// do
while(true)
{
try
{
socket.Listen(5);
Socket newSocket=socket.Accept();
newSocket.Receive(byteMessage);
string sTime = DateTime.Now.ToShortTimeString ( ) ;
string msg=sTime+":"+"Message from:";
msg+=newSocket.RemoteEndPoint.ToString()+Encoding.Default.GetString(byteMessage);
this.listBox1.Items.Add(msg);
}
catch(SocketException ex)
{
this.label1.Text+=ex.ToString();
}
}
// while(byteMessage!=null);
}
//开始监听
private void button1_Click(object sender, System.EventArgs e)
{
try
{
mythread = new Thread(new ThreadStart(BeginListen));
mythread.Start();
}
catch(System.Exception er)
{
MessageBox.Show(er.Message,"完成",MessageBoxButtons.OK,MessageBoxIcon.Stop);
}
}
客户端:
using System.Net;
using System.Net.Sockets;
using System.Text;
private void button1_Click(object sender, System.EventArgs e)
{
BeginSend();
}
private void BeginSend()
{
string ip=this.txtip.Text;
string port=this.txtport.Text;
IPAddress serverIp=IPAddress.Parse(ip);
int serverPort=Convert.ToInt32(port);
IPEndPoint iep=new IPEndPoint(serverIp,serverPort);
byte[] byteMessage;
// do
// {
Socket socket=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
socket.Connect(iep);
byteMessage=Encoding.ASCII.GetBytes(textBox1.Text);
socket.Send(byteMessage);
socket.Shutdown(SocketShutdown.Both);
socket.Close();
// }
// while(byteMessage!=null);
}
- Socket通信基础
- Socket通信基础
- JAVA-Socket通信基础
- Android socket通信基础
- Socket通信基础
- 基础Socket通信
- python socket基础通信
- Socket通信基础
- SOCKET通信基础
- 网络通信Socket编程基础
- Socket通信基础篇(一)
- JAVA-socket通信基础(1)
- JAVA-socket通信基础(2)
- JAVA-socket通信基础(1)
- JAVA-socket通信基础(2)
- socket通信基础知识点记录
- java基础之Socket通信
- socket通信基础(一)
- 常用正则表达式
- Tomcat 服务器server.xml的关键参数配置
- 3DMAX SDK语法高亮配置
- 他们是这样描述美女的,球星皮耶罗的绯闻女友该如何描述?
- 关于3DMAX SDK Class_Id
- Socket通信基础
- UNIX下的信号问题
- listView使用小结
- javascript技巧参考
- MFC程序中检查内存泄漏的手段
- ActionScript 3的HTTPTunnel的实现[转]
- JDK1.4 & GCC2.95 install guide --
- VC数据类型
- 名字由来