socket通信服务器端怎么写

socket通信服务器端怎么写,第1张

Android客户端与PC服务器实现Socket通信(wifi)

本文介绍Android终端持续扫描AP信息并发送给服务器端的实现。首先基于TCP协议在Android终端和PC两端之间形成网络虚拟链路。使用ServerSocket创建TCP服务器端,然后在Android客户端使用Socket的构造器来连接服务器。其中Android终端通过WIFI连接和PC处于同一局域网。

1.

PC服务器启用ServerSocket

两个通信实体在建立虚拟链路之前,需要有一方先准备好,主动接受来自其他通信实体的连接请求。

使用ServerSocket对象监听来自客户端的Socket连接

//创建ServerSocket对象

//by wayne from www.cnblog.com/dwayne/

ServerSocket ss = new ServerSocket(30000)

//监听来自客户端的请求

while(true){

Socket s = ss.accept()

}

如果没有连接,则将一直处于等待状态。

当接收到连接请求后,获取消息到输入流,并保存到文件。

//接收客户端消息

//by wayne from www.cnblog.com/dwayne/

BufferedReader in = new BufferedReader(new

InputStreamReader(client.getInputStream()))

String str

BufferedWriter bw = new BufferedWriter(new FileWriter("D:/ApInfo"+ (i++)

+".txt"))

while ((str = in.readLine()) != null) {

System.out.println(str)

bw.write(str)

bw.newLine()

}

2.

Android终端使用Socket通信

客户端使用Socket的构造器连接服务器,指定服务器IP和端口号就可以了。

Socket s = new

Socket(“192.168.1.100”, 30000)

这样服务器端的accept()方法就得到响应,从而向下执行,服务器端和客户端就形成了一对互相连接的Socket。再进行通信时就没有服务器和客户端之分了,都是通过输入输出流进行通信。

详细步骤

采用Handler和TimerTask来定时扫描AP信息并发送给服务器端。

TimerTask规定了到达指定的时间所要进行的任务。

TimerTask task = new TimerTask(){

public void run() {

Message message = new Message()

message.what = 1

handler.sendMessage(message)

}

}

handler传递message内容:

Handler handler = new Handler(){

public void handleMessage(Message msg) {

switch (msg.what) {

case 1:

// 执行定时器时间到了之后由handler传递的任务

break

}

super.handleMessage(msg)

}

}

因为需要持续执行扫描任务,所以启用新线程执行定时任务

//启动单独线程定时向服务器发送AP信息

//by wayne from www.cnblogs.com/dwayne

new Thread(){

@Override

public void run() {

// TODO Auto-generated method stub

timer.schedule(task, 2000,10000)//在2秒后每10秒执行一次定时器中的方法

}

}.start()

接下来扫描AP信息并发送给服务器端,然后将结果保存。

WifiManager wifiManager=(WifiManager) getSystemService(WIFI_SERVICE)

wifiManager.startScan()

mWifiList = wifiManager.getScanResults()

由WifiManager说明可知,它可以用于处理已配置的网络,当前连接的网络及AP信息的扫描等情况。

This class provides the primary API for managing all aspects of

Wi-Fi connectivity. Get an instance of this class by calling

Context.getSystemService(Context.WIFI_SERVICE). It deals with several categories

of items:

The list of configured networks. The list can be viewed and updated, and

attributes of individual entries can be modified.

The currently active Wi-Fi network, if any. Connectivity can be established

or torn down, and dynamic information about the state of the network can be

queried.

Results of access point scans, containing enough information to make

decisions about what access point to connect to.

It defines the names of various Intent actions that are broadcast upon any

sort of change in Wi-Fi state.

向服务器发送消息:

socket = new Socket("192.168.1.211",30000)

//向服务器端发送消息

PrintWriter out = new PrintWriter( new BufferedWriter( new

OutputStreamWriter(socket.getOutputStream())),true)

out.println(message)

其中message为获取的AP信息

测试收到的信息格式为:

SSID: ICIS_LAB, BSSID: 1c:af:f7:9a:65:e4, capabilities:

[WPA-PSK-TKIP+CCMP], level: -80, frequency: 2

namespace SocketTest{ class Program{public static void SendMessage(){Socket socket = serverSocket.Accept() Console.WriteLine("Connected a client:{0}",socket.RemoteEndPoint) socket.Send(Encoding.ASCII.GetBytes("welcome to server")) //Thread thread = new Thread(ReceiveMessage) // thread.Start() }public static void ReceiveMessage(object obj){Socket socket = (Socket)obj byte[] data = new byte[1024] int len = socket.Receive(data) string dataString = Encoding.ASCII.GetString(data, 0, len) Console.WriteLine("Receive Data:{0} from {1}", dataString,socket.RemoteEndPoint) //Thread thread = new Thread(SendMessage) //thread.Start(socket) }static Socket serverSocket static void Main(string[] args){//定义接收数据长度变量int recv //定义接收数据的缓存byte[] data = new byte[1024] //定义侦听端口IPEndPoint ipEnd = new IPEndPoint(IPAddress.Any, 5566) //定义套接字类型serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) //连接serverSocket.Bind(ipEnd) //开始侦听serverSocket.Listen(10) //控制台输出侦听状态Console.Write("Waiting for a client") //Socket client while (true){//一旦接受连接,创建一个客户端Socket client = serverSocket.Accept() //获取客户端的IP和端口IPEndPoint ipEndClient = (IPEndPoint)client.RemoteEndPoint //输出客户端的IP和端口Console.WriteLine("Connect with {0} at port {1}", ipEndClient.Address, ipEndClient.Port) //定义待发送字符string welcome = "Welcome to my server" //数据类型转换data = Encoding.ASCII.GetBytes(welcome) while (true){ try{//发送client.Send(data, data.Length, SocketFlags.None) //接收数据可以用线程也可以不用//ReceiveMessage(client) Thread thread = new Thread(ReceiveMessage) thread.Start(client) ////对data清零//data = new byte[1024] ////获取收到的数据的长度//recv = client.Receive(data) ////如果收到的数据长度为0,则退出//if (recv == 0)//break ////输出接收到的数据//Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv)) //将接收到的数据再发送出去// client.Send(data, recv, SocketFlags.None) }catch (Exception){client.Close() serverSocket.Close() }}client.Close() }//Console.WriteLine("Disconnect form{0}", ipEndClient.Address) serverSocket.Close()}}}

<soapenv:Header/>

<soapenv:Body>

<api:getEmp>

<shopId>string</shopId>

</api:getEmp>

</soapenv:Body>

</soapenv:Envelope>

这个时SOAP协议的标准报文格式,客户端只要发送这样的报文给支持SOAP协议的webservice服务器即可成功调用web service服务

服务端:部署服务只需要自己定义服务的接口和实现类,并用@webservice注解,通过endPoint类直接发布即可


欢迎分享,转载请注明来源:夏雨云

原文地址:https://www.xiayuyun.com/zonghe/290286.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-04-23
下一篇2023-04-23

发表评论

登录后才能评论

评论列表(0条)

    保存