百度
360搜索
搜狗搜索

socket通信实例,Socket 通信之 UDP 通信详细介绍

本文目录一览: 使用Socket发送和接收消息[2]

——此文章摘自《ASP NET网络数据库开发实例精解》定价 ¥ 特价 ¥ 详细>>//track linktech cn/?m_id=dangdang&a_id=A &l= &l_type = width= height= border= nosave> .创建被发送的文件myFile txt
在应用程序Example_ _ 的根目录下创建使用Socket发送的文件myFile txt 它为一个text类型的文本文件 其内容如图 所示
//develop csai cn/dotnet_ASP/images/ jpg >图 被发送的myFile txt文件
.设计页面MySocket aspx的事件和函数
页面MySocket aspx调用函数Page_Load(object sender System EventArgs e)初始化 该函数调用函数SocketSend()发送文件信息 函数SocketSend()首先创建发送信息的Socket对象 并定义发送的IP 地址和端口 然后读取myFile txt文件的信息 最后再调用函数Send()发送文件的数据 函数Page_Load(object sender System EventArgs e)和函数SocketSend()的程序代码如下 private void Page_Load(object sender System EventArgs e) { if(!Page IsPostBack) { //发送数据 SocketSend(); } } private void SocketSend() { //创建发送数据的Socket Socket sendsocket = new Socket(AddressFamily InterNeork SocketType Stream ProtocolType Tcp); //设置发送数据的地址 IPEndPoint endPoint = new IPEndPoint(IPAddress Parse( ) ); //创建读取文件的流 FileStream fileSteam = new FileStream(Server MapPath( myFile txt ) FileMode OpenOrCreate FileAccess Read); //文件大小 Byte[] fsSize = new Byte[fileSteam Length ]; //读取文件的二进制流 BinaryReader reader = new BinaryReader(fileSteam); //读取数据 reader Read(fsSize (int)fileSteam Length ); //链接目的地 sendsocket Connect(endPoint); //发送数据 sendsocket Send(fsSize); //关闭文件流

lishixinzhi/Article/program/net/201311/15235

C语言socket编程怎么实现2个客户端之间通信

如果只是两个客户端和一个服务器,可通过服务器转发即可,两个客户端连接到服务器,服务器把从A接收到的发给B,把从B接收到的发给A即可,如果要做成多个客户端的,则要给各个客户端分配ID,服务端好根据各个客户端和消息要转发送给客户端的ID来确定消息发送对象。
网络的Socket数据传输是一种特殊的I/O,Socket也是一种文件描述符。Socket也具有一个类似于打开文件的函数调用Socket(),该函数返回一个整型的Socket描述符,随后的连接建立、数据传输等操作都是通过该Socket实现的。
下面用Socket实现一个windows下的c语言socket通信例子,这里我们客户端传递一个字符串,服务器端进行接收。
【服务器端】#include "stdafx.h"#include

#include

#include

#define SERVER_PORT 5208 //侦听端口void main(){ WORD wVersionRequested; WSADATA wsaData; int ret, nLeft, length; SOCKET sListen, sServer; //侦听套接字,连接套接字 struct sockaddr_in saServer, saClient; //地址信息 char *ptr;//用于遍历信息的指针 //WinSock初始化 wVersionRequested=MAKEWORD(2, 2); //希望使用的WinSock DLL 的版本 ret=WSAStartup(wVersionRequested, &wsaData); if(ret!=0) { printf("WSAStartup() failed!\n"); return; } //创建Socket,使用TCP协议 sListen=socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (sListen == INVALID_SOCKET) { WSACleanup(); printf("socket() faild!\n"); return; } //构建本地地址信息 saServer.sin_family = AF_INET; //地址家族 saServer.sin_port = htons(SERVER_PORT); //注意转化为网络字节序 saServer.sin_addr.S_un.S_addr = htonl(INADDR_ANY); //使用INADDR_ANY 指示任意地址 //绑定 ret = bind(sListen, (struct sockaddr *)&saServer, sizeof(saServer)); if (ret == SOCKET_ERROR) { printf("bind() faild! code:%d\n", WSAGetLastError()); closesocket(sListen); //关闭套接字 WSACleanup(); return; } //侦听连接请求 ret = listen(sListen, 5); if (ret == SOCKET_ERROR) { printf("listen() faild! code:%d\n", WSAGetLastError()); closesocket(sListen); //关闭套接字 return; } printf("Waiting for client connecting!\n"); printf("Tips: Ctrl+c to quit!\n"); //阻塞等待接受客户端连接 while(1)//循环监听客户端,永远不停止,所以,在本项目中,我们没有心跳包。 { length = sizeof(saClient); sServer = accept(sListen, (struct sockaddr *)&saClient, &length); if (sServer == INVALID_SOCKET) { printf("accept() faild! code:%d\n", WSAGetLastError()); closesocket(sListen); //关闭套接字 WSACleanup(); return; } char receiveMessage[5000]; nLeft = sizeof(receiveMessage); ptr = (char *)&receiveMessage; while(nLeft>0) { //接收数据 ret = recv(sServer, ptr, 5000, 0); if (ret == SOCKET_ERROR) { printf("recv() failed!\n"); return; } if (ret == 0) //客户端已经关闭连接 { printf("Client has closed the connection\n"); break; } nLeft -= ret; ptr += ret; } printf("receive message:%s\n", receiveMessage);//打印我们接收到的消息。 } // closesocket(sListen); // closesocket(sServer); // WSACleanup();}【客户端】#include "stdafx.h"#include

#include

#include

#define SERVER_PORT 5208 //侦听端口void main(){ WORD wVersionRequested; WSADATA wsaData; int ret; SOCKET sClient; //连接套接字 struct sockaddr_in saServer; //地址信息 char *ptr; BOOL fSuccess = TRUE; //WinSock初始化 wVersionRequested = MAKEWORD(2, 2); //希望使用的WinSock DLL的版本 ret = WSAStartup(wVersionRequested, &wsaData); if(ret!=0) { printf("WSAStartup() failed!\n"); return; } //确认WinSock DLL支持版本2.2 if(LOBYTE(wsaData.wVersion)!=2 || HIBYTE(wsaData.wVersion)!=2) { WSACleanup(); printf("Invalid WinSock version!\n"); return; } //创建Socket,使用TCP协议 sClient = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (sClient == INVALID_SOCKET) { WSACleanup(); printf("socket() failed!\n"); return; } //构建服务器地址信息 saServer.sin_family = AF_INET; //地址家族 saServer.sin_port = htons(SERVER_PORT); //注意转化为网络节序 saServer.sin_addr.S_un.S_addr = inet_addr("192.168.1.127"); //连接服务器 ret = connect(sClient, (struct sockaddr *)&saServer, sizeof(saServer)); if (ret == SOCKET_ERROR) { printf("connect() failed!\n"); closesocket(sClient); //关闭套接字 WSACleanup(); return; } char sendMessage[]="hello this is client message!"; ret = send (sClient, (char *)&sendMessage, sizeof(sendMessage), 0); if (ret == SOCKET_ERROR) { printf("send() failed!\n"); } else printf("client info has been sent!"); closesocket(sClient); //关闭套接字 WSACleanup();}

Java Socket初步详解

  网络编程的基本模型就是客户机到服务器模型 简单的说就是两个进程之间相互通讯 然后其中一个必须提供一个固定的位置 而另一个则只需要知道这个固定的位置 并去建立两者之间的联系 然后完成数据的通讯就可以了 这里提供固定位置的通常称为服务器 而建立联系的通常叫做客户端 基于这个简单的模型 就可以进入网络编程啦
  Java对这个模型的支持有很多种Api 而这里我只想介绍有关Socket的编程接口 对于Java而言已经简化了Socket的编程接口 首先我们来讨论有关提供固定位置的服务方是如何建立的 Java提供了ServerSocket来对其进行支持 事实上当你创建该类的一个实力对象并提供一个端口资源你就建立了一个固定位置可以让其他计算机来访问你 ServerSocket server=new ServerSocket( );这里稍微要注意的是端口的分配必须是唯一的 因为端口是为了唯一标识每台计算机唯一服务的 另外端口号是从 ~ 之间的 前 个端口已经被Tcp/Ip 作为保留端口 因此你所分配的端口只能是 个之后的 好了 我们有了固定位置 现在所需要的就是一根连接线了 该连接线由客户方首先提出要求 因此Java同样提供了一个Socket对象来对其进行支持 只要客户方创建一个Socket的实例对象进行支持就可以了 Socket client
  =new Socket(InetAddress getLocalHost() );客户机必须知道有关服务器的IP地址 对于著一点Java也提供了一个相关的类InetAddress 该对象的实例必须通过它的静态方法来提供 它的静态方法主要提供了得到本机IP 和通过名字或IP直接得到InetAddress的方法
  上面的方法基本可以建立一条连线让两台计算机相互交流了 可是数据是如何传输的呢?事实上I/O操作总是和网络编程息息相关的 因为底层的网络是继续数据的 除非远程调用 处理问题的核心在执行上 否则数据的交互还是依赖于IO操作的 所以你也必须导入java io这个包 java的IO操作也不复杂 它提供了针对于字节流和Unicode的读者和写者 然后也提供了一个缓冲用于数据的读写
  BufferedReader in=new BufferedReader(new InputStreamReader(server getInputStream()));

  PrintWriter out=new PrintWriter(server getOutputStream());
  上面两句就是建立缓冲并把原始的字节流转变为Unicode可以操作 而原始的字节流来源于Socket的两个方法 getInputStream()和getOutputStream()方 分别用来得到输入和输出 那么现在有了基本的模型和基本的操作工具 我们可以做一个简单的Socket例程了
  服务方:
  import java io *;
  import *;
  public class MyServer {
  public static void main(String[] args) throws IOException{
  ServerSocket server=new ServerSocket( );
  Socket client=server accept();
  BufferedReader in=new BufferedReader(new InputStreamReader(client getInputStream()));
  PrintWriter out=new PrintWriter(client getOutputStream());
  while(true){
  String str=in readLine();
  System out println(str);
  out println( has receive );
  out flush();
  if(str equals( end ))
  break;
  }
  client close();
  }
  }
  这个程序的主要目的在于服务器不断接收客户机所写入的信息只到 客户机发送 End 字符串就退出程序 并且服务器也会做出 Receive 为回应 告知客户机已接收到消息
  客户机代码:
  import *;
  import java io *;
  public class Client{
  static Socket server;
  public static void main(String[] args)throws Exception{
  server=new Socket(InetAddress getLocalHost() );
  BufferedReader in=new BufferedReader(new InputStreamReader(server getInputStream()));
  PrintWriter out=new PrintWriter(server getOutputStream());
  BufferedReader wt=new BufferedReader(new InputStreamReader(System in));
  while(true){
  String str=wt readLine();
  out println(str);
  out flush();
  if(str equals( end )){
  break;
  }
  System out println(in readLine());
  }
  server close();
  }
  }
  客户机代码则是接受客户键盘输入 并把该信息输出 然后输出 End 用来做退出标识
  这个程序只是简单的两台计算机之间的通讯 如果是多个客户同时访问一个服务器呢?你可以试着再运行一个客户端 结果是会抛出异常的 那么多个客户端如何实现呢?
  其实 简单的分析一下 就可以看出客户和服务通讯的主要通道就是Socket本身 而服务器通过accept方法就是同意和客户建立通讯 这样当客户建立Socket的同时 服务器也会使用这一根连线来先后通讯 那么既然如此只要我们存在多条连线就可以了 那么我们的程序可以变为如下:
  服务器:
  import java io *;
  import *;
  public class MyServer {
  public static void main(String[] args) throws IOException{
  ServerSocket server=new ServerSocket( );
  while(true){
  Socket client=server accept();
  BufferedReader in=new BufferedReader(new InputStreamReader(client getInputStream()));
  PrintWriter out=new PrintWriter(client getOutputStream());
  while(true){
  String str=in readLine();
  System out println(str);
  out println( has receive );
  out flush();
  if(str equals( end ))
  break;
  }
  client close();
  }
  }
  }
  这里仅仅只是加了一个外层的While循环 这个循环的目的就是当一个客户进来就为它分配一个Socket直到这个客户完成一次和服务器的交互 这里也就是接受到客户的 End 消息 那么现在就实现了多客户之间的交互了 但是 问题又来了 这样做虽然解决了多客户 可是是排队执行的 也就是说当一个客户和服务器完成一次通讯之后下一个客户才可以进来和服务器交互 无法做到同时服务 那么要如何才能同时达到既能相互之间交流又能同时交流呢?很显然这是一个并行执行的问题了 所以线程是最好的解决方案
  那么下面的问题是如何使用线程 首先要做的事情是创建线程并使得其可以和网络连线取得联系 然后由线程来执行刚才的操作 要创建线程要么直接继承Thread要么实现Runnable接口 要建立和Socket的联系只要传递引用就可以了 而要执行线程就必须重写run方法 而run方法所做的事情就是刚才单线程版本main所做的事情 因此我们的程序变成了这样:
  import *;
  import java io *;
  public class MultiUser extends Thread{
  private Socket client;
  public MultiUser(Socket c){
  this client=c;
  }
  public void run(){
  try{
  BufferedReader in=new BufferedReader(new InputStreamReader(client getInputStream()));
  PrintWriter out=new PrintWriter(client getOutputStream());
  //Mutil User but can t parallel
  while(true){
  String str=in readLine();
  System out println(str);
  out println( has receive );
  out flush();
  if(str equals( end ))
  break;
  }
  client close();
  }catch(IOException ex){
  }finally{
  }
  }
  public static void main(String[] args)throws IOException{
  ServerSocket server=new ServerSocket( );
  while(true){
  //transfer location change Single User or Multi User
  MultiUser mu=new MultiUser(server accept());
  mu start();
  }
  }
  }
lishixinzhi/Article/program/Java/hx/201311/27013

怎么用java的socket进行文件传输?谁能给个简单的例子,包括发送端和接收端。

java中的网络信息传输方式是基于TCP协议或者UD协议P的,socket是基于TCP协议的
例子1
(1)客户端程序:
import java.io.*;
import java.net.*;
public class Client
{ public static void main(String args[])
{ String s=null;
Socket mysocket;
DataInputStream in=null;
DataOutputStream out=null;
try{
mysocket=new Socket("localhost",4331);
in=new DataInputStream(mysocket.getInputStream());
out=new DataOutputStream(mysocket.getOutputStream());
out.writeUTF("你好!");//通过 out向"线路"写入信息。
while(true)
{
s=in.readUTF();//通过使用in读取服务器放入"线路"里的信息。堵塞状态,
//除非读取到信息。
out.writeUTF(":"+Math.random());
System.out.println("客户收到:"+s);
Thread.sleep(500);
}
}
catch(IOException e)
{ System.out.println("无法连接");
}
catch(InterruptedException e){}
}
}
(2)服务器端程序:
import java.io.*;import java.net.*;
public class Server
{ public static void main(String args[])
{ ServerSocket server=null;
Socket you=null;String s=null;
DataOutputStream out=null;DataInputStream in=null;
try{ server=new ServerSocket(4331);}
catch(IOException e1){System.out.println("ERRO:"+e1);}
try{ you=server.accept();
in=new DataInputStream(you.getInputStream());
out=new DataOutputStream(you.getOutputStream());
while(true)
{
s=in.readUTF();// 通过使用in读取客户放入"线路"里的信息。堵塞状态,
//除非读取到信息。
out.writeUTF("你好:我是服务器");//通过 out向"线路"写入信息.
out.writeUTF("你说的数是:"+s);
System.out.println("服务器收到:"+s);
Thread.sleep(500);
}
}
catch(IOException e)
{ System.out.println(""+e);
}
catch(InterruptedException e){}
}
}
例子(2)
(1) 客户端
import java.net.*;import java.io.*;
import java.awt.*;import java.awt.event.*;
import java.applet.*;
public class Computer_client extends Applet implements Runnable,ActionListener
{ Button 计算;TextField 输入三边长度文本框,计算结果文本框;
Socket socket=null;
DataInputStream in=null; DataOutputStream out=null;
Thread thread;
public void init()
{ setLayout(new GridLayout(2,2));
Panel p1=new Panel(),p2=new Panel();
计算=new Button(" 计算");
输入三边长度文本框=new TextField(12);计算结果文本框=new TextField(12);
p1.add(new Label("输入三角形三边的长度,用逗号或空格分隔:"));
p1.add( 输入三边长度文本框);
p2.add(new Label("计算结果:"));p2.add(计算结果文本框);p2.add(计算);
计算.addActionListener(this);
add(p1);add(p2);
}
public void start()
{ try
{ //和小程序所驻留的服务器建立套接字连接:
socket = new Socket(this.getCodeBase().getHost(), 4331);
in =new DataInputStream(socket.getInputStream());
out = new DataOutputStream(socket.getOutputStream());
}
catch (IOException e){}
if(thread == null)
{ thread = new Thread(this);
thread.start();
}
}
public void run()
{ String s=null;
while(true)
{ try{ s=in.readUTF();//堵塞状态,除非读取到信息。
计算结果文本框.setText(s);
}
catch(IOException e)
{ 计算结果文本框.setText("与服务器已断开");
break;
}
}
}
public void actionPerformed(ActionEvent e)
{ if(e.getSource()==计算)
{ String s=输入三边长度文本框.getText();
if(s!=null)
{ try { out.writeUTF(s);
}
catch(IOException e1){}
}
}
}
}
(2) 服务器端
import java.io.*;import java.net.*;
import java.util.*;import java.sql.*;
public class Computer_server
{ public static void main(String args[])
{ ServerSocket server=null;Server_thread thread;
Socket you=null;
while(true)
{ try{ server=new ServerSocket(4331);
}
catch(IOException e1)
{ System.out.println("正在监听"); //ServerSocket对象不能重复创建。
}
try{ you=server.accept();
System.out.println("客户的地址:"+you.getInetAddress());
}
catch (IOException e)
{ System.out.println("正在等待客户");
}
if(you!=null)
{ new Server_thread(you).start(); //为每个客户启动一个专门的线程。
}
else
{ continue;
}
}
}
}
class Server_thread extends Thread
{ Socket socket;Connection Con=null;Statement Stmt=null;
DataOutputStream out=null;DataInputStream in=null;int n=0;
String s=null;
Server_thread(Socket t)
{ socket=t;
try { in=new DataInputStream(socket.getInputStream());
out=new DataOutputStream(socket.getOutputStream());
}
catch (IOException e)
{}
}
public void run()
{ while(true)
{ double a[]=new double[3] ;int i=0;
try{ s=in.readUTF();堵塞状态,除非读取到信息。
StringTokenizer fenxi=new StringTokenizer(s," ,");
while(fenxi.hasMoreTokens())
{ String temp=fenxi.nextToken();
try{ a[i]=Double.valueOf(temp).doubleValue();i++;
}
catch(NumberFormatException e)
{ out.writeUTF("请输入数字字符");
}
}
double p=(a[0]+a[1]+a[2])/2.0;
out.writeUTF(" "+Math.sqrt(p*(p-a[0])*(p-a[1])*(p-a[2])));
sleep(2);
}
catch(InterruptedException e){}
catch (IOException e)
{ System.out.println("客户离开");
break;
}
}
}
}
这些例子都是Java2实用教程上的.

阅读更多 >>>  linux服务器tail命令

Socket 通信之 UDP 通信

前段时间,我们在 这篇文章 中谈到了多进程和进程之间的通信方式,主要谈到了本地进程之间使用队列(Queue)进程通信,如果我们要通信的进程不在同一台主机上,我们就无法使用队列进行通信了,这时就需要使用 Socket(套接字)。
Socket 是应用层和传输层之间的一层抽象协议,可以用来进行进程间通信,一般有 UDP 和 TCP 两种通信方式,前者速度稍快,稳定性不好,无法丢包重传。后者速度稍慢一点,但稳定性很好,可以丢包重传。
本文首先介绍使用 Socket 进行 UDP 通信。

使用 Socket 进行 UDP 通信的流程如下:

下面依次进行讲解。

要进行 Socket 通信,我们需要使用 socket 模块,首先需要创建一个 Socket 对象。下面是两种创建方式:

如果我们需要向别的主机发送数据,我们需要改主机的 IP 地址和相应的端口号。在使用 Socket 进行通信时,需要将两个信息写在一元组中,元组的第一项为目标主机 IP 地址,第二项为接受数据的端口号:

其中,IP 地址使用字符串类型,端口号使用数字类型。

如果不绑定端口,每次使用 Socket 时都会由操作系统动态分配一个端口,我们也可以绑定为某个固定的端口。这样做的好处是:如果我们想要接受其他主机的信息,其他主机可以直接向这个端口发送数据,如果使用动态端口的话,发送方并不知道目标端口是什么,因此无法向接收方发送数据。
绑定端口需要使用 Socket 对象的 bind 方法:

bind 方法接受一个元组作为参数,元组的第一项为绑定的 IP 地址,第二项为绑定的端口号。我们可以把第一项指定为本机上的任意一个 IP 地址,也可以设置为一个空字符串 "" ,表示本机上任意合法的 IP 地址。

使用 UDP 套接字协议时,发送数据使用 Socket 对象的 sendto 方法,接受数据使用 Socket 对象的 recvfrom 方法。这两个方法的使用方式如下:

sendto 方法接受两个参数:发送的数据和目标主机的 IP 和端口元组,在 Python3 中,发送的数据应该转为 byte 类型发送,Python2 中可以直接发送字符串。
recvfrom 接受一个参数:本次接受的最大数据尺寸。该方法是阻塞的,只有在接收到数据后才能进行后续的操作。

就像使用文件那样,在使用完套接字后,需要关闭它,调用 close 方法即可。

上面我们介绍了 Socket 的使用方式,下面我们来做一个单工通信的例子(一方负责发送信息,一方负责接收信息)。
我们这里来创建两个文件:用以发送信息的 send.py 和用以接收信息的 recv.py。该实例在虚拟机中模拟(注意将虚拟机设置为桥接模式)。
创建 send.py:

创建 recv.py:

运行结果如下:

上面实现了一个单工通信的例子:一方负责发,一方负责接收。下面我们继续实现一个双工通信的例子,使双方都能够收发消息。
由于接收和发送消息时是使用 while 循环不断轮询的,因此要实现同时发送和接受,我们需要进行多任务处理。
新建一个 msg.py:

这里我们使用 3000 端口发送数据,3001 端口接收数据,运行程序时只需填写目标主机的 IP 地址,就可以进行通信。
运行效果:

我们还可以进行局域网内的广播,只需对 Socket 加上一条设置:

同时,发送广播需要一个广播地址,以及目标主机接受广播的端口:

上面的设置只能给 0 网段的主机发送广播,要想给局域网中所有的主机发送广播,可以这样设置:

下面我们新建一个 send.py 用来发送广播:

新建一个 recv.py 用来接收广播:

运行效果如图:

完。

C#谁能给我个,CS 通过Socket与线程通信的例子,,

Socket异步通讯:
我做的一个网络联机小游戏上NetWork部分代码!可能能帮你解决问题!
Server:
http://code.google.com/p/shortboom/source/browse/trunk/NetWork/GameServer.cs
Client:
http://code.google.com/p/shortboom/source/browse/trunk/NetWork/GameClient.cs
可以使用 FlyTCPFramework
如果需要请我联系
也可以到我的网站来交流http://www.bg1jt.cn
VS2003下的:
//======================客户端=========================
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace S_c
{
public class Form1 : System.Windows.Forms.Form
{
private IPEndPoint ipendpoint;
private Socket localsocket;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox textBox1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.TextBox textBox2;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.GroupBox groupBox2;
private System.Windows.Forms.RichTextBox richTextBox1;
private System.Windows.Forms.GroupBox groupBox3;
private System.Windows.Forms.RichTextBox richTextBox2;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.Button button3;
private System.Windows.Forms.StatusBar statusBar1;
private System.Windows.Forms.StatusBarPanel statusBarPanel1;
private System.Windows.Forms.StatusBarPanel statusBarPanel2;
private System.ComponentModel.Container components = null;
public Form1()
{
InitializeComponent();
}
protected override void Dispose( bool disposing )
{
if( disposing ){
if (components != null){
components.Dispose();
}
}
base.Dispose( disposing );
}
private void InitializeComponent()
{
this.button1 = new System.Windows.Forms.Button();
this.label1 = new System.Windows.Forms.Label();
this.textBox1 = new System.Windows.Forms.TextBox();
this.label2 = new System.Windows.Forms.Label();
this.textBox2 = new System.Windows.Forms.TextBox();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.groupBox2 = new System.Windows.Forms.GroupBox();
this.richTextBox1 = new System.Windows.Forms.RichTextBox();
this.groupBox3 = new System.Windows.Forms.GroupBox();
this.richTextBox2 = new System.Windows.Forms.RichTextBox();
this.button2 = new System.Windows.Forms.Button();
this.button3 = new System.Windows.Forms.Button();
this.statusBar1 = new System.Windows.Forms.StatusBar();
this.statusBarPanel1 = new System.Windows.Forms.StatusBarPanel();
this.statusBarPanel2 = new System.Windows.Forms.StatusBarPanel();
this.groupBox1.SuspendLayout();
this.groupBox2.SuspendLayout();
this.groupBox3.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.statusBarPanel1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.statusBarPanel2)).BeginInit();
this.SuspendLayout();
this.button1.Location = new System.Drawing.Point(208, 32);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(64, 56);
this.button1.TabIndex = 0;
this.button1.Text = "Begin Connect";
this.button1.Click += new System.EventHandler(this.button1_Click);
this.label1.Location = new System.Drawing.Point(8, 32);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(56, 23);
this.label1.TabIndex = 1;
this.label1.Text = "HostIP:";
this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
this.textBox1.Location = new System.Drawing.Point(64, 32);
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(128, 21);
this.textBox1.TabIndex = 2;
this.textBox1.Text = "127.0.0.1";
this.label2.Location = new System.Drawing.Point(8, 64);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(56, 23);
this.label2.TabIndex = 1;
this.label2.Text = "Port:";
this.label2.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
this.textBox2.Location = new System.Drawing.Point(64, 64);
this.textBox2.Name = "textBox2";
this.textBox2.Size = new System.Drawing.Size(128, 21);
this.textBox2.TabIndex = 2;
this.textBox2.Text = "";
this.groupBox1.Controls.Add(this.label1);
this.groupBox1.Controls.Add(this.label2);
this.groupBox1.Controls.Add(this.textBox2);
this.groupBox1.Controls.Add(this.textBox1);
this.groupBox1.Controls.Add(this.button1);
this.groupBox1.Location = new System.Drawing.Point(24, 8);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(296, 112);
this.groupBox1.TabIndex = 3;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Connect";
this.groupBox2.Controls.Add(this.richTextBox1);
this.groupBox2.Location = new System.Drawing.Point(24, 128);
this.groupBox2.Name = "groupBox2";
this.groupBox2.Size = new System.Drawing.Size(296, 176);
this.groupBox2.TabIndex = 4;
this.groupBox2.TabStop = false;
this.groupBox2.Text = "Receive Messages";
this.richTextBox1.Dock = System.Windows.Forms.DockStyle.Fill;
this.richTextBox1.Location = new System.Drawing.Point(3, 17);
this.richTextBox1.Name = "richTextBox1";
this.richTextBox1.Size = new System.Drawing.Size(290, 156);
this.richTextBox1.TabIndex = 0;
this.richTextBox1.Text = "";
this.groupBox3.Controls.Add(this.richTextBox2);
this.groupBox3.Location = new System.Drawing.Point(24, 312);
this.groupBox3.Name = "groupBox3";
this.groupBox3.Size = new System.Drawing.Size(296, 176);
this.groupBox3.TabIndex = 5;
this.groupBox3.TabStop = false;
this.groupBox3.Text = "Send Messages";
this.richTextBox2.Dock = System.Windows.Forms.DockStyle.Fill;
this.richTextBox2.Location = new System.Drawing.Point(3, 17);
this.richTextBox2.Name = "richTextBox2";
this.richTextBox2.Size = new System.Drawing.Size(290, 156);
this.richTextBox2.TabIndex = 0;
this.richTextBox2.Text = "";
this.button2.Location = new System.Drawing.Point(69, 496);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(64, 23);
this.button2.TabIndex = 6;
this.button2.Text = "SEND";
this.button2.Click += new System.EventHandler(this.button2_Click);
this.button3.Location = new System.Drawing.Point(208, 496);
this.button3.Name = "button3";
this.button3.Size = new System.Drawing.Size(64, 23);
this.button3.TabIndex = 6;
this.button3.Text = "REWRITE";
this.statusBar1.Location = new System.Drawing.Point(0, 535);
this.statusBar1.Name = "statusBar1";
this.statusBar1.Panels.AddRange(new System.Windows.Forms.StatusBarPanel[] { this.statusBarPanel1,this.statusBarPanel2});
this.statusBar1.ShowPanels = true;
this.statusBar1.Size = new System.Drawing.Size(344, 22);
this.statusBar1.TabIndex = 7;
this.statusBarPanel1.Text = "Current Status:";
this.statusBarPanel2.Width = 350;
this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
this.ClientSize = new System.Drawing.Size(344, 557);
this.Controls.Add(this.statusBar1);
this.Controls.Add(this.button2);
this.Controls.Add(this.groupBox2);
this.Controls.Add(this.groupBox1);
this.Controls.Add(this.groupBox3);
this.Controls.Add(this.button3);
this.Name = "Form1";
this.Text = "S_c";
this.groupBox1.ResumeLayout(false);
this.groupBox2.ResumeLayout(false);
this.groupBox3.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.statusBarPanel1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.statusBarPanel2)).EndInit();
this.ResumeLayout(false);
}
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
private void button1_Click(object sender, System.EventArgs e)
{
try{
ipendpoint=new IPEndPoint(IPAddress.Parse(textBox1.Text.Trim()),int.Parse(textBox2.Text.Trim()));}
catch{
statusBar1.Panels[1].Text="Please input a valid value!";
return;
}
Thread thread=new Thread(new ThreadStart(accp));
thread.Start();
}
private void accp(){
try{
localsocket=new Socket(localsocket.Connect(ipendpoint);}
catch{
statusBar1.Panels[1].Text="Host not found!";
return;
}statusBar1.Panels[1].Text="Has connected to host-->"+ipendpoint.ToString();
Thread thread=new Thread(new ThreadStart(getmsg));
thread.Start();
}
private void getmsg(){
while(true){
byte[] buffer=new byte[128];
localsocket.Receive(buffer);
richTextBox1.AppendText("\n"+System.Text.Encoding.BigEndianUnicode.GetString(buffer));
}
}
private void button2_Click(object sender, System.EventArgs e){
buffer=System.Text.Encoding.BigEndianUnicode.GetBytes(richTextBox2.Text.Trim());
localsocket.Send(buffer);
}
}
}
//======================服务端=========================
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace S_s
{ public class Form1 : System.Windows.Forms.Form
{
private IPEndPoint ipendpoint;
private Socket localsocket;
private Socket remotesocket;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox textBox1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.TextBox textBox2;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.GroupBox groupBox2;
private System.Windows.Forms.RichTextBox richTextBox1;
private System.Windows.Forms.GroupBox groupBox3;
private System.Windows.Forms.RichTextBox richTextBox2;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.Button button3;
private System.Windows.Forms.StatusBar statusBar1;
private System.Windows.Forms.StatusBarPanel statusBarPanel1;
private System.Windows.Forms.StatusBarPanel statusBarPanel2;
private System.ComponentModel.Container components = null;
public Form1()
{
InitializeComponent();
}
protected override void Dispose( bool disposing )
{
if( disposing ){
if (components != null) {
components.Dispose();
}
}
base.Dispose( disposing );
}
private void InitializeComponent()
{
this.button1 = new System.Windows.Forms.Button();
this.label1 = new System.Windows.Forms.Label();
this.textBox1 = new System.Windows.Forms.TextBox();
this.label2 = new System.Windows.Forms.Label();
this.textBox2 = new System.Windows.Forms.TextBox();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.groupBox2 = new System.Windows.Forms.GroupBox();
this.richTextBox1 = new System.Windows.Forms.RichTextBox();
this.groupBox3 = new System.Windows.Forms.GroupBox();
this.richTextBox2 = new System.Windows.Forms.RichTextBox();
this.button2 = new System.Windows.Forms.Button();
this.button3 = new System.Windows.Forms.Button();
this.statusBar1 = new System.Windows.Forms.StatusBar();
this.statusBarPanel1 = new System.Windows.Forms.StatusBarPanel();
this.statusBarPanel2 = new System.Windows.Forms.StatusBarPanel();
this.groupBox1.SuspendLayout();
this.groupBox2.SuspendLayout();
this.groupBox3.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.statusBarPanel1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.statusBarPanel2)).BeginInit();
this.SuspendLayout();
this.button1.Location = new System.Drawing.Point(208, 32);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(64, 56);
this.button1.TabIndex = 0;
this.button1.Text = "Begin Listen";
this.button1.Click += new System.EventHandler(this.button1_Click);
this.label1.Location = new System.Drawing.Point(8, 32);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(56, 23);
this.label1.TabIndex = 1;
this.label1.Text = "HostIP:";
this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
this.textBox1.Location = new System.Drawing.Point(64, 32);
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(128, 21);
this.textBox1.TabIndex = 2;
this.textBox1.Text = "127.0.0.1";
this.label2.Location = new System.Drawing.Point(8, 64);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(56, 23);
this.label2.TabIndex = 1;
this.label2.Text = "Port:";
this.label2.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
this.textBox2.Location = new System.Drawing.Point(64, 64);
this.textBox2.Name = "textBox2";
this.textBox2.Size = new System.Drawing.Size(128, 21);
this.textBox2.TabIndex = 2;
this.textBox2.Text = "";
this.groupBox1.Controls.Add(this.label1);
this.groupBox1.Controls.Add(this.label2);
this.groupBox1.Controls.Add(this.textBox2);
this.groupBox1.Controls.Add(this.textBox1);
this.groupBox1.Controls.Add(this.button1);
this.groupBox1.Location = new System.Drawing.Point(24, 8);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(296, 112);
this.groupBox1.TabIndex = 3;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Listen";
this.groupBox2.Controls.Add(this.richTextBox1);
this.groupBox2.Location = new System.Drawing.Point(24, 128);
this.groupBox2.Name = "groupBox2";
this.groupBox2.Size = new System.Drawing.Size(296, 176);
this.groupBox2.TabIndex = 4;
this.groupBox2.TabStop = false;
this.groupBox2.Text = "Receive Messages";
this.richTextBox1.Dock = System.Windows.Forms.DockStyle.Fill;
this.richTextBox1.Location = new System.Drawing.Point(3, 17);
this.richTextBox1.Name = "richTextBox1";
this.richTextBox1.Size = new System.Drawing.Size(290, 156);
this.richTextBox1.TabIndex = 0;
this.richTextBox1.Text = "";
this.groupBox3.Controls.Add(this.richTextBox2);
this.groupBox3.Location = new System.Drawing.Point(24, 312);
this.groupBox3.Name = "groupBox3";
this.groupBox3.Size = new System.Drawing.Size(296, 176);
this.groupBox3.TabIndex = 5;
this.groupBox3.TabStop = false;
this.groupBox3.Text = "Send Messages";
this.richTextBox2.Dock = System.Windows.Forms.DockStyle.Fill;
this.richTextBox2.Location = new System.Drawing.Point(3, 17);
this.richTextBox2.Name = "richTextBox2";
this.richTextBox2.Size = new System.Drawing.Size(290, 156);
this.richTextBox2.TabIndex = 0;
this.richTextBox2.Text = "";
this.button2.Location = new System.Drawing.Point(69, 496);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(64, 23);
this.button2.TabIndex = 6;
this.button2.Text = "SEND";
this.button2.Click += new System.EventHandler(this.button2_Click);
this.button3.Location = new System.Drawing.Point(208, 496);
this.button3.Name = "button3";
this.button3.Size = new System.Drawing.Size(64, 23);
this.button3.TabIndex = 6;
this.button3.Text = "REWRITE";
this.statusBar1.Location = new System.Drawing.Point(0, 535);
this.statusBar1.Name = "statusBar1";
this.statusBar1.Panels.AddRange(new System.Windows.Forms.StatusBarPanel[] { this.statusBarPanel1,this.statusBarPanel2});
this.statusBar1.ShowPanels = true;
this.statusBar1.Size = new System.Drawing.Size(344, 22);
this.statusBar1.TabIndex = 7;
this.statusBarPanel1.Text = "Current Status:";
this.statusBarPanel2.Width = 350;
this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
this.ClientSize = new System.Drawing.Size(344, 557);
this.Controls.Add(this.statusBar1);
this.Controls.Add(this.button2);
this.Controls.Add(this.groupBox2);
this.Controls.Add(this.groupBox1);
this.Controls.Add(this.groupBox3);
this.Controls.Add(this.button3);
this.Name = "Form1";
this.Text = "S_s";
this.groupBox1.ResumeLayout(false);
this.groupBox2.ResumeLayout(false);
this.groupBox3.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.statusBarPanel1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.statusBarPanel2)).EndInit();
this.ResumeLayout(false);
}
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
private void button1_Click(object sender, System.EventArgs e)
{
try
{
ipendpoint=new IPEndPoint(IPAddress.Parse(textBox1.Text.Trim()),int.Parse(textBox2.Text.Trim()));
}
catch
{
statusBar1.Panels[1].Text="Please input a valid value!";
return;
}

阅读更多 >>>  linux拆分压缩命令

Thread thread=new Thread(new ThreadStart(accp));
thread.Start();
}

private void accp()
{
while(true)
{
try
{
localsocket=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
localsocket.Bind(ipendpoint);
localsocket.Listen(128);
}
catch
{statusBar1.Panels[1].Text="Host not found or Listen has began!";
return;
}
statusBar1.Panels[1].Text="Listen has bengin!";

while(true)
{remotesocket=localsocket.Accept();
Thread thread=new Thread(new ThreadStart(getmsg));
thread.Start();
}
}
}
private void getmsg()
{
while(true)
{
byte[] buffer=new byte[128];
remotesocket.Receive(buffer);
richTextBox1.AppendText("\n"+System.Text.Encoding.BigEndianUnicode.GetString(buffer));
}
}
private void button2_Click(object sender, System.EventArgs e)
{
byte[] buffer=System.Text.Encoding.BigEndianUnicode.GetBytes(DateTime.Now+"\n"+richTextBox2.Text.Trim());
remotesocket.Send(buffer);
}
}
}

java里如何向所有人发送信息,通过socket

服务器端和客户端都是通过SOCKET来进行通信的,首先产生一个 socket实例,通过这个实例,服务器端调用accept这个方法接收来自客户端发送的信息.但是在产生socket实例的时候必须初始化一个端口.用来负责接受客户端的请求! 客户端要给服务器发送消息也必须产生一个socket实例,初始化的时候必须指定服务器的IP地址,并且指定服务接收的端口号,这样客户端才能找到服务器要接收的地方,找到地方就可以发送过去了。和你写信一样。找到地址 BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); PrintWriter out = new PrintWriter(socket.getOutputStream()); BufferedReader wt = new BufferedReader(new InputStreamReader(System.in)); 这个只是用来获取一个从键盘的一个流.传送给服务器端的数据都是通过流来表示的。意思是是键盘输入的一个字节转化成字符流.并输出或者写入!

Socket通信原理

Socket 通信原理 Socket 博客地址 Socket 是一组调用接口、是 { 应用层与 TCP/IP 协议族 } 通信的中间软件抽象层 . 调用接口是 TCP/IP 协议族的 API 函数
TCP/IP协议族包括传输层、网络层、链路层 TCP、UDP、IP、ICMP、IGMP、ARP、RARP
Socket接口将复杂的TCP/IP协议族隐藏,给用户提供一组简单的接口就是全部,让Socket去组织数据以符合指定的协议。
socket的基本操作 socket()函数、bind()函数、listen()函数、 connect()函数、accept()函数、 read()函数、write()函数、close()函数等
Unix/Linux基本哲学之一就是一切皆文件 都可以用 open –> write/read –> close 模式来操作
服务器端: socket() —> bind() —> listen() —> accept() —> read() || write() —> close() —客户端: socket() —> connect() —> wirte() || read() —> close()
服务器:创建并初始化socket实例、绑定端口号、监听端口号、阻塞等待客户端连接 客户端:创建并初始化socket实例、连接服务器、连接成功即TCP双向通信通道建立
客户端发送请求数据、服务器接受请求数据、 服务器处理请求数据、 服务器发送响应数据、客户端接受响应数据、 客户端与服务器关闭连接,此双向交互结束。

谁能给一个 Qt 跟 java 用socket通讯的例子,要求java 做服务端,qt 做客户端,要求双方都能实时显示对方发过

QT直接访问java的socket吗?一般我在linux下使用QT做UI,使用ACE来实现socket通信,你可以试试ACE,很好用,这段时间就在64位Ubuntu下使用ACE和java通信。
有JAVA 做个web服务器,发布几个webservers ,在QT客户端里面通过webservers 调用就可以了啊。
是基于SOAP协议的。效率么socket 效率高,一般还是可以用的。
提供一个聊天功能的给你
import java.net.*;
import java.io.*;
class My1 extends Thread
{
private Socket skt;
public My1(Socket skt)
{
this.skt = skt;
}
public void run()
{
try
{
BufferedReader br = new BufferedReader(new InputStreamReader(skt.getInputStream()));

for(;;)
{
if(br.readLine()==null) {break;}
System.out.println(br.readLine()); // 阻塞
}
}
catch(Exception e)
{
System.out.println("对方断线!");
}
}
}
class My2 extends Thread
{
private Socket skt;
public My2(Socket skt)
{
this.skt = skt;
}
public void run()
{
try
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(skt.getOutputStream());

for(;;)
{
pw.println("姓名====>:"+br.readLine()); // 阻塞
pw.flush();
}
}
catch(Exception e)
{
System.out.println("对方断线!");
}
}
}
public class Good
{
public static void main(String[] args) throws Exception
{
//连接的目的是:获得Socket对象
Socket skt;

System.out.print("请输入

或者:

,

");

// 先选择角色

String[] ss = new BufferedReader(new InputStreamReader(System.in)).readLine().split(",");

if(ss.length==1)

skt = new ServerSocket(Integer.parseInt(ss[0])).accept();

else

skt = new Socket(ss[0], Integer.parseInt(ss[1]));

System.out.println("连接到:" + skt.getInetAddress().getHostAddress());

// 连接建立,角色消失

new My1(skt).start(); //读网络

new My2(skt).start(); //读键盘

}

}

C#socket异步怎么实现 线程间通信如何实现

给个例子吧, 下面是从网页链接转载的源代码, 我看过, 可以供参考, 希望能帮到你
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Text;
// State object for receiving data from remote device.
public class StateObject
{
// Client socket.
public Socket workSocket = null;
// Size of receive buffer.
public const int BufferSize = 256;
// Receive buffer.
public byte[] buffer = new byte[BufferSize];
// Received data string.
public StringBuilder sb = new StringBuilder();
}
public class AsynchronousClient
{
// The port number for the remote device.
private const int port = 11000;
// ManualResetEvent instances signal completion.
private static ManualResetEvent connectDone =
new ManualResetEvent(false);
private static ManualResetEvent sendDone =
new ManualResetEvent(false);
private static ManualResetEvent receiveDone =
new ManualResetEvent(false);
// The response from the remote device.
private static String response = String.Empty;
private static void StartClient()
{
// Connect to a remote device.
try
{
// Establish the remote endpoint for the socket.
// The name of the
// remote device is "host.contoso.com".
IPHostEntry ipHostInfo = Dns.Resolve("host.contoso.com");
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);
// Create a TCP/IP socket.
Socket client = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
// Connect to the remote endpoint.
client.BeginConnect(remoteEP,
new AsyncCallback(ConnectCallback), client);
connectDone.WaitOne();
// Send test data to the remote device.
Send(client, "This is a test

");

sendDone.WaitOne();

// Receive the response from the remote device.

Receive(client);

receiveDone.WaitOne();

// Write the response to the console.

Console.WriteLine("Response received : {0}", response);

// Release the socket.

client.Shutdown(SocketShutdown.Both);

client.Close();

}

catch (Exception e)

{

Console.WriteLine(e.ToString());

}

}

private static void ConnectCallback(IAsyncResult ar)

{

try

{

// Retrieve the socket from the state object.

Socket client = (Socket)ar.AsyncState;

// Complete the connection.

client.EndConnect(ar);

Console.WriteLine("Socket connected to {0}",

client.RemoteEndPoint.ToString());

// Signal that the connection has been made.

connectDone.Set();

}

catch (Exception e)

{

Console.WriteLine(e.ToString());

}

}

private static void Receive(Socket client)

{

try

{

// Create the state object.

StateObject state = new StateObject();

state.workSocket = client;

// Begin receiving the data from the remote device.

client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,

new AsyncCallback(ReceiveCallback), state);

}

catch (Exception e)

{

Console.WriteLine(e.ToString());

}

}

private static void ReceiveCallback(IAsyncResult ar)

{

try

{

// Retrieve the state object and the client socket

// from the asynchronous state object.

StateObject state = (StateObject)ar.AsyncState;

Socket client = state.workSocket;

// Read data from the remote device.

int bytesRead = client.EndReceive(ar);

if (bytesRead > 0)

{

// There might be more data, so store the data received so far.

state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));

// Get the rest of the data.

client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,

new AsyncCallback(ReceiveCallback), state);

}

else

{

// All the data has arrived; put it in response.

if (state.sb.Length > 1)

{

response = state.sb.ToString();

}

// Signal that all bytes have been received.

receiveDone.Set();

}

}

catch (Exception e)

{

Console.WriteLine(e.ToString());

}

}

private static void Send(Socket client, String data)

{

// Convert the string data to byte data using ASCII encoding.

byte[] byteData = Encoding.ASCII.GetBytes(data);

// Begin sending the data to the remote device.

client.BeginSend(byteData, 0, byteData.Length, 0,

new AsyncCallback(SendCallback), client);

}

private static void SendCallback(IAsyncResult ar)

{

try

{

// Retrieve the socket from the state object.

Socket client = (Socket)ar.AsyncState;

// Complete sending the data to the remote device.

int bytesSent = client.EndSend(ar);

Console.WriteLine("Sent {0} bytes to server.", bytesSent);

// Signal that all bytes have been sent.

sendDone.Set();

}

catch (Exception e)

{

Console.WriteLine(e.ToString());

}

}

public static int Main(String[] args)

{

StartClient();

return 0;

}

}

事件 或者 action 做回调

基于C#的socket编程的TCP异步实现

一、摘要

  本篇博文阐述基于TCP通信协议的异步实现。

二、实验平台

  Visual Studio 2010

三、异步通信实现原理及常用方法

3.1 建立连接 

  在同步模式中,在服务器上使用Accept方法接入连接请求,而在客户端则使用Connect方法来连接服务器。相对地,在异步模式下,服务器可以使用BeginAccept方法和EndAccept方法来完成连接到客户端的任务,在客户端则通过BeginConnect方法和EndConnect方法来实现与服务器的连接。

  BeginAccept在异步方式下传入的连接尝试,它允许其他动作而不必等待连接建立才继续执行后面程序。在调用BeginAccept之前,必须使用Listen方法来侦听是否有连接请求,BeginAccept的函数原型为:

BeginAccept(AsyncCallback AsyncCallback, Ojbect state)

参数:

AsyncCallBack:代表回调函数

state:表示状态信息,必须保证state中包含socket的句柄

  使用BeginAccept的基本流程是:

(1)创建本地终节点,并新建套接字与本地终节点进行绑定;

(2)在端口上侦听是否有新的连接请求;

(3)请求开始接入新的连接,传入Socket的实例或者StateOjbect的实例。

  参考代码:

复制代码

//定义IP地址

IPAddress local = IPAddress.Parse("127.0,0,1");

IPEndPoint iep = new IPEndPoint(local,13000);

//创建服务器的socket对象

Socket server = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);

server.Bind(iep);

server.Listen(20);

server.BeginAccecpt(new AsyncCallback(Accept),server);

复制代码

  当BeginAccept()方法调用结束后,一旦新的连接发生,将调用回调函数,而该回调函数必须包括用来结束接入连接操作的EndAccept()方法。

该方法参数列表为 Socket EndAccept(IAsyncResult iar)

下面为回调函数的实例:

复制代码

void Accept(IAsyncResult iar)

{

//还原传入的原始套接字

Socket MyServer = (Socket)iar.AsyncState;

//在原始套接字上调用EndAccept方法,返回新的套接字

Socket service = MyServer.EndAccept(iar);

}

复制代码

  至此,服务器端已经准备好了。客户端应通过BeginConnect方法和EndConnect来远程连接主机。在调用BeginConnect方法时必须注册相应的回调函数并且至少传递一个Socket的实例给state参数,以保证EndConnect方法中能使用原始的套接字。下面是一段是BeginConnect的调用:

Socket socket=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp)

IPAddress ip=IPAddress.Parse("127.0.0.1");

IPEndPoint iep=new IPEndPoint(ip,13000);

socket.BeginConnect(iep, new AsyncCallback(Connect),socket);

  EndConnect是一种阻塞方法,用于完成BeginConnect方法的异步连接诶远程主机的请求。在注册了回调函数后必须接收BeginConnect方法返回的IASynccReuslt作为参数。下面为代码演示:

复制代码

void Connect(IAsyncResult iar)

{

Socket client=(Socket)iar.AsyncState;

try

{

client.EndConnect(iar);

}

catch (Exception e)

{

Console.WriteLine(e.ToString());

}

finally

{

}

}

复制代码

  除了采用上述方法建立连接之后,也可以采用TcpListener类里面的方法进行连接建立。下面是服务器端对关于TcpListener类使用BeginAccetpTcpClient方法处理一个传入的连接尝试。以下是使用BeginAccetpTcpClient方法和EndAccetpTcpClient方法的代码:

复制代码

public static void DoBeginAccept(TcpListener listner)

{

//开始从客户端监听连接

Console.WriteLine("Waitting for a connection");

//接收连接

//开始准备接入新的连接,一旦有新连接尝试则调用回调函数DoAcceptTcpCliet

listner.BeginAcceptTcpClient(new AsyncCallback(DoAcceptTcpCliet), listner);

}

//处理客户端的连接

public static void DoAcceptTcpCliet(IAsyncResult iar)

{

//还原原始的TcpListner对象

TcpListener listener = (TcpListener)iar.AsyncState;

//完成连接的动作,并返回新的TcpClient

TcpClient client = listener.EndAcceptTcpClient(iar);

Console.WriteLine("连接成功");

}

复制代码

  代码的处理逻辑为:

(1)调用BeginAccetpTcpClient方法开开始连接新的连接,当连接视图发生时,回调函数被调用以完成连接操作;

(2)上面DoAcceptTcpCliet方法通过AsyncState属性获得由BeginAcceptTcpClient传入的listner实例;

(3)在得到listener对象后,用它调用EndAcceptTcpClient方法,该方法返回新的包含客户端信息的TcpClient。

  BeginConnect方法和EndConnect方法可用于客户端尝试建立与服务端的连接,这里和第一种方法并无区别。下面看实例:

复制代码

public void doBeginConnect(IAsyncResult iar)

{

Socket client=(Socket)iar.AsyncState;

//开始与远程主机进行连接

client.BeginConnect(serverIP[0],13000,requestCallBack,client);

Console.WriteLine("开始与服务器进行连接");

}

private void requestCallBack(IAsyncResult iar)

{

try

{

//还原原始的TcpClient对象

TcpClient client=(TcpClient)iar.AsyncState;

//

client.EndConnect(iar);

Console.WriteLine("与服务器{0}连接成功",client.Client.RemoteEndPoint);

}

catch(Exception e)

{

Console.WriteLine(e.ToString());

}

finally

{

}

}

复制代码

  以上是建立连接的两种方法。可根据需要选择使用。

3.2 发送与接受数据

  在建立了套接字的连接后,就可以服务器端和客户端之间进行数据通信了。异步套接字用BeginSend和EndSend方法来负责数据的发送。注意在调用BeginSend方法前要确保双方都已经建立连接,否则会出异常。下面演示代码:

复制代码

private static void Send(Socket handler, String data)

{

// Convert the string data to byte data using ASCII encoding.

byte[] byteData = Encoding.ASCII.GetBytes(data);

// Begin sending the data to the remote device.

handler.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), handler);

}

private static void SendCallback(IAsyncResult ar)

{

try

{

// Retrieve the socket from the state object.

Socket handler = (Socket)ar.AsyncState;

// Complete sending the data to the remote device.

int bytesSent = handler.EndSend(ar);

Console.WriteLine("Sent {0} bytes to client.", bytesSent);

handler.Shutdown(SocketShutdown.Both);

handler.Close();

}

catch (Exception e)

{

Console.WriteLine(e.ToString());

}

}

复制代码

  接收数据是通过BeginReceive和EndReceive方法:

复制代码

private static void Receive(Socket client)

{

try

{

// Create the state object.

StateObject state = new StateObject();

state.workSocket = client;

// Begin receiving the data from the remote device.

client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);

}

catch (Exception e)

{

Console.WriteLine(e.ToString());

}

}

private static void ReceiveCallback(IAsyncResult ar)

{

try

{

// Retrieve the state object and the client socket

// from the asynchronous state object.

StateObject state = (StateObject)ar.AsyncState;

Socket client = state.workSocket;

// Read data from the remote device.

int bytesRead = client.EndReceive(ar);

if (bytesRead > 0)

{

// There might be more data, so store the data received so far.

state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));

// Get the rest of the data.

client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);

}

else

{

// All the data has arrived; put it in response.

if (state.sb.Length > 1)

{

response = state.sb.ToString();

}

// Signal that all bytes have been received.

receiveDone.Set();

}

}

catch (Exception e)

{

Console.WriteLine(e.ToString());

}

}

复制代码

  上述代码的处理逻辑为:

(1)首先处理连接的回调函数里得到的通讯套接字client,接着开始接收数据;

(2)当数据发送到缓冲区中,BeginReceive方法试图从buffer数组中读取长度为buffer.length的数据块,并返回接收到的数据量bytesRead。最后接收并打印数据。

  

  除了上述方法外,还可以使用基于NetworkStream相关的异步发送和接收方法,下面是基于NetworkStream相关的异步发送和接收方法的使用介绍。

  NetworkStream使用BeginRead和EndRead方法进行读操作,使用BeginWreite和EndWrete方法进行写操作,下面看实例:

复制代码

static void DataHandle(TcpClient client)

{

TcpClient tcpClient = client;

//使用TcpClient的GetStream方法获取网络流

NetworkStream ns = tcpClient.GetStream();

//检查网络流是否可读

if(ns.CanRead)

{

//定义缓冲区

byte[] read = new byte[1024];

ns.BeginRead(read,0,read.Length,new AsyncCallback(myReadCallBack),ns);

}

else

{

Console.WriteLine("无法从网络中读取流数据");

}

}

public static void myReadCallBack(IAsyncResult iar)

{

NetworkStream ns = (NetworkStream)iar.AsyncState;

byte[] read = new byte[1024];

String data = "";

int recv;

recv = ns.EndRead(iar);

data = String.Concat(data, Encoding.ASCII.GetString(read, 0, recv));

//接收到的消息长度可能大于缓冲区总大小,反复循环直到读完为止

while (ns.DataAvailable)

{

ns.BeginRead(read, 0, read.Length, new AsyncCallback(myReadCallBack), ns);

}

//打印

Console.WriteLine("您收到的信息是" + data);

}

复制代码

3.3 程序阻塞与异步中的同步问题

  .Net里提供了EventWaitHandle类来表示一个线程的同步事件。EventWaitHandle即事件等待句柄,他允许线程通过操作系统互发信号和等待彼此的信号来达到线程同步的目的。这个类有2个子类,分别为AutoRestEevnt(自动重置)和ManualRestEvent(手动重置)。下面是线程同步的几个方法:

(1)Rset方法:将事件状态设为非终止状态,导致线程阻塞。这里的线程阻塞是指允许其他需要等待的线程进行阻塞即让含WaitOne()方法的线程阻塞;

(2)Set方法:将事件状态设为终止状态,允许一个或多个等待线程继续。该方法发送一个信号给操作系统,让处于等待的某个线程从阻塞状态转换为继续运行,即WaitOne方法的线程不在阻塞;

(3)WaitOne方法:阻塞当前线程,直到当前的等待句柄收到信号。此方法将一直使本线程处于阻塞状态直到收到信号为止,即当其他非阻塞进程调用set方法时可以继续执行。

复制代码

public static void StartListening()

{

// Data buffer for incoming data.

byte[] bytes = new Byte[1024];

// Establish the local endpoint for the socket.

// The DNS name of the computer

// running the listener is "host.contoso.com".

//IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());

//IPAddress ipAddress = ipHostInfo.AddressList[0];

IPAddress ipAddress = IPAddress.Parse("127.0.0.1");

IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);

// Create a TCP/IP socket.

Socket listener = new Socket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp);

// Bind the socket to the local

//endpoint and listen for incoming connections.

try

{

listener.Bind(localEndPoint);

listener.Listen(100);

while (true)

{

// Set the event to nonsignaled state.

allDone.Reset();

// Start an asynchronous socket to listen for connections.

Console.WriteLine("Waiting for a connection...");

listener.BeginAccept(new AsyncCallback(AcceptCallback),listener);

// Wait until a connection is made before continuing.

allDone.WaitOne();

}

}

catch (Exception e)

{

Console.WriteLine(e.ToString());

}

Console.WriteLine("\nPress ENTER to continue...");

Console.Read();

}

复制代码

  上述代码的逻辑为:

(1)试用了ManualRestEvent对象创建一个等待句柄,在调用BeginAccept方法前使用Rest方法允许其他线程阻塞;

(2)为了防止在连接完成之前对套接字进行读写操作,务必要在BeginAccept方法后调用WaitOne来让线程进入阻塞状态。

  当有连接接入后系统会自动调用会调用回调函数,所以当代码执行到回调函数时说明连接已经成功,并在函数的第一句就调用Set方法让处于等待的线程可以继续执行。

阅读更多 >>>  Linux中的copy命令

网站数据信息

"socket通信实例,Socket 通信之 UDP 通信"浏览人数已经达到18次,如你需要查询该站的相关权重信息,可以点击进入"Chinaz数据" 查询。更多网站价值评估因素如:socket通信实例,Socket 通信之 UDP 通信的访问速度、搜索引擎收录以及索引量、用户体验等。 要评估一个站的价值,最主要还是需要根据您自身的需求,如网站IP、PV、跳出率等!