當前位置:首頁 » 雲伺服器 » socket怎麼寫伺服器

socket怎麼寫伺服器

發布時間: 2022-04-30 05:47:30

㈠ c#怎麼寫一個伺服器端的socket

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(); } }}

㈡ socket編程怎麼寫一個客戶端和兩個服務端

網路的Socket數據傳輸是一種特殊的I/O,Socket也是一種文件描述符。Socket也具有一個類似於打開文件的函數調用Socket(),該函數返回一個整型的Socket描述符,隨後的連接建立、數據傳輸等操作都是通過該Socket實現的。
下面用Socket實現一個windows下的c語言socket通信例子,這里我們客戶端傳遞一個字元串,伺服器端進行接收。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
【伺服器端】
#include "stdafx.h"
#include <stdio.h>
#include <winsock2.h>
#include <winsock2.h>
#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 <stdio.h>
#include <stdlib.h>
#include <winsock2.h>
#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();
}

python怎麼建立socket服務端

socket伺服器再細分可分為多種了,tcp,udp,websocket,都是調用socket模塊,但是具體實現起來有一點細微的差別

先給出一個tcp和udp通過socket協議實現的聊天室的例子

python聊天室(python2.7版本):

都是分別運行server.py和client.py,就可以進行通訊了。

TCP版本:

socket-tcp-server.py(服務端):

#-*-encoding:utf-8-*-
#socket.getaddrinfo(host,port,family=0,socktype=0,proto=0,flags=0)
#根據給定的參數host/port,相應的轉換成一個包含用於創建socket對象的五元組,
#參數host為域名,以字元串形式給出代表一個IPV4/IPV6地址或者None.
#參數port如果字元串形式就代表一個服務名,比如「http」"ftp""email"等,或者為數字,或者為None
#參數family為地主族,可以為AF_INET,AF_INET6,AF_UNIX.
#參數socktype可以為SOCK_STREAM(TCP)或者SOCK_DGRAM(UDP)
#參數proto通常為0可以直接忽略
#參數flags為AI_*的組合,比如AI_NUMERICHOST,它會影響函數的返回值
#附註:給參數host,port傳遞None時建立在C基礎,通過傳遞NULL。
#該函數返回一個五元組(family,socktype,proto,canonname,sockaddr),同時第五個參數sockaddr也是一個二元組(address,port)
#更多的方法及鏈接請訪問
#Echoserverprogram
fromsocketimport*
importsys
importthreading
fromtimeimportctime
fromtimeimportlocaltime
importtraceback
importtime
importsubprocess
reload(sys)
sys.setdefaultencoding("utf8")


HOST='127.0.0.1'
PORT=8555#設置偵聽埠
BUFSIZ=1024

classTcpServer():
def__init__(self):
self.ADDR=(HOST,PORT)
try:
self.sock=socket(AF_INET,SOCK_STREAM)
print'%disopen'%PORT

self.sock.bind(self.ADDR)
self.sock.listen(5)
#設置退出條件
self.STOP_CHAT=False

#所有監聽的客戶端
self.clients={}
self.thrs={}
self.stops=[]

exceptException,e:
print"%disdown"%PORT
returnFalse

defIsOpen(ip,port):

s=socket(AF_INET,SOCK_STREAM)
try:
s.connect((ip,int(port)))
#s.shutdown(2)
#利用shutdown()函數使socket雙向數據傳輸變為單向數據傳輸。shutdown()需要一個單獨的參數,
#該參數表示s了如何關閉socket。具體為:0表示禁止將來讀;1表示禁止將來寫;2表示禁止將來讀和寫。
print'%disopen'%port
returnTrue
except:
print'%disdown'%port
returnFalse

deflisten_client(self):
whilenotself.STOP_CHAT:
print(u'等待接入,偵聽埠:%d'%(PORT))
self.tcpClientSock,self.addr=self.sock.accept()
print(u'接受連接,客戶端地址:',self.addr)
address=self.addr
#將建立的clientsocket鏈接放到列表self.clients中
self.clients[address]=self.tcpClientSock
#分別將每個建立的鏈接放入進程中,接收且分發消息
self.thrs[address]=threading.Thread(target=self.readmsg,args=[address])
self.thrs[address].start()
time.sleep(0.5)defreadmsg(self,address):
#如果地址不存在,則返回False
ifaddressnotinself.clients:
returnFalse
#得到發送消息的clientsocket
client=self.clients[address]
whileTrue:
try:
#獲取到消息內容data
data=client.recv(BUFSIZ)
except:
print(e)
self.close_client(address)
break
ifnotdata:
break
#python3使用bytes,所以要進行編碼
#s='%s發送給我的信息是:[%s]%s'%(addr[0],ctime(),data.decode('utf8'))
#對日期進行一下格式化
ISOTIMEFORMAT='%Y-%m-%d%X'
stime=time.strftime(ISOTIMEFORMAT,localtime())
s=u'%s發送給我的信息是:%s'%(str(address),data.decode('utf8'))
#將獲得的消息分發給鏈接中的clientsocket
forkinself.clients:
self.clients[k].send(s.encode('utf8'))
self.clients[k].sendall('sendall:'+s.encode('utf8'))
printstr(k)
print([stime],':',data.decode('utf8'))
#如果輸入quit(忽略大小寫),則程序退出
STOP_CHAT=(data.decode('utf8').upper()=="QUIT")
ifSTOP_CHAT:
print"quit"
self.close_client(address)
print"alreadyquit"
break

defclose_client(self,address):
try:
client=self.clients.pop(address)
self.stops.append(address)
client.close()
forkinself.clients:
self.clients[k].send(str(address)+u"已經離開了")
except:
pass
print(str(address)+u'已經退出')


if__name__=='__main__':
tserver=TcpServer()
tserver.listen_client()

——————————華麗的分割線——————————

socket-tcp-client.py(客戶端):

#-*-encoding:utf-8-*-
fromsocketimport*
importsys
importthreading
importtime
reload(sys)
sys.setdefaultencoding("utf8")


#測試,連接本機
HOST='127.0.0.1'
#設置偵聽埠
PORT=8555
BUFSIZ=1024

classTcpClient:

ADDR=(HOST,PORT)
def__init__(self):
self.HOST=HOST
self.PORT=PORT
self.BUFSIZ=BUFSIZ
#創建socket連接
self.client=socket(AF_INET,SOCK_STREAM)
self.client.connect(self.ADDR)
#起一個線程,監聽接收的信息
self.trecv=threading.Thread(target=self.recvmsg)
self.trecv.start()

defsendmsg(self):
#循環發送聊天消息,如果socket連接存在則一直循環,發送quit時關閉鏈接
whileself.client.connect_ex(self.ADDR):
data=raw_input('>:')
ifnotdata:
break
self.client.send(data.encode('utf8'))
print(u'發送信息到%s:%s'%(self.HOST,data))
ifdata.upper()=="QUIT":
self.client.close()
printu"已關閉"
break
defrecvmsg(self):
#接收消息,如果鏈接一直存在,則持續監聽接收消息
try:
whileself.client.connect_ex(self.ADDR):
data=self.client.recv(self.BUFSIZ)
print(u'從%s收到信息:%s'%(self.HOST,data.decode('utf8')))
exceptException,e:
printstr(e)

if__name__=='__main__':
client=TcpClient()
client.sendmsg()

UDP版本:

socket-udp-server.py

#-*-coding:utf8-*-

importsys
importtime
importtraceback
importthreading
reload(sys)
sys.setdefaultencoding('utf-8')

importsocket
importtraceback

HOST="127.0.0.1"
PORT=9555
CHECK_PERIOD=20
CHECK_TIMEOUT=15

classUdpServer(object):
def__init__(self):
self.clients=[]
self.beats={}
self.ADDR=(HOST,PORT)
try:
self.sock=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
self.sock.bind(self.ADDR)#綁定同一個域名下的所有機器
self.beattrs=threading.Thread(target=self.checkheartbeat)
self.beattrs.start()
exceptException,e:
traceback.print_exc()
returnFalse

deflisten_client(self):
whileTrue:
time.sleep(0.5)
print"hohohohohoo"
try:
recvData,address=self.sock.recvfrom(2048)
ifnotrecvData:
self.close_client(address)
break
ifaddressinself.clients:
senddata=u"%s發送給我的信息是:%s"%(str(address),recvData.decode('utf8'))
ifrecvData.upper()=="QUIT":
self.close_client(address)
ifrecvData=="HEARTBEAT":
self.heartbeat(address)
continue
else:
self.clients.append(address)
senddata=u"%s發送給我的信息是:%s"%(str(address),u'進入了聊天室')
forcinself.clients:
try:
self.sock.sendto(senddata,c)
exceptException,e:
printstr(e)
self.close_client(c)
exceptException,e:
#traceback.print_exc()
printstr(e)
pass

defheartbeat(self,address):
self.beats[address]=time.time()

defcheckheartbeat(self):

whileTrue:
print"checkheartbeat"
printself.beats
try:
forcinself.clients:
printtime.time()
printself.beats[c]
ifself.beats[c]+CHECK_TIMEOUT<time.time():
printu"%s心跳超時,連接已經斷開"%str(c)
self.close_client(c)
else:
printu"checkp%s,沒有斷開"%str(c)
exceptException,e:
traceback.print_exc()
printstr(e)
pass
time.sleep(CHECK_PERIOD)

defclose_client(self,address):
try:
ifaddressinself.clients:
self.clients.remove(address)
ifself.beats.has_key(address):
delself.beats[address]
printself.clients
forcinself.clients:
self.sock.sendto(u'%s已經離開了'%str(address),c)
print(str(address)+u'已經退出')
exceptException,e:
printstr(e)
raise

if__name__=="__main__":
udpServer=UdpServer()
udpServer.listen_client()

——————————華麗的分割線——————————
socket-udp-client.py:
#-*-coding:utf8-*-

importsys
importthreading
importtime
reload(sys)
sys.setdefaultencoding('utf-8')

importsocket

HOST="127.0.0.1"
PORT=9555
#BEAT_PORT=43278
BEAT_PERIOD=5


classUdpClient(object):
def__init__(self):
self.clientsock=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
self.HOST=HOST
self.ADDR=(HOST,PORT)
self.clientsock.sendto(u'請求建立鏈接',self.ADDR)
self.recvtrs=threading.Thread(target=self.recvmsg)
self.recvtrs.start()
self.hearttrs=threading.Thread(target=self.heartbeat)
self.hearttrs.start()

defsendmsg(self):
whileTrue:
data=raw_input(">:")
ifnotdata:
break
self.clientsock.sendto(data.encode('utf-8'),self.ADDR)
ifdata.upper()=='QUIT':
self.clientsock.close()
break

defheartbeat(self):
whileTrue:
self.clientsock.sendto('HEARTBEAT',self.ADDR)
time.sleep(BEAT_PERIOD)

defrecvmsg(self):
whileTrue:
recvData,addr=self.clientsock.recvfrom(1024)
ifnotrecvData:
break
print(u'從%s收到信息:%s'%(self.HOST,recvData.decode('utf8')))if__name__=="__main__":
udpClient=UdpClient()
udpClient.sendmsg()

㈣ 我想問下如何在手機上建立一個伺服器,用Socket的方法如何實現。

TCP方式:
TCP協議客戶端實現:

//創建一個Socket對象,指定伺服器端的IP地址和埠號
Socketsocket=newSocket("192.168.1.104",4567);
//使用InputStream讀取硬碟上的文件,這里只是用文件當做信息源,可以讀取控制項用戶輸入信息
InputStreaminputStream=new
FileInputStream("f://file/words.txt");

//從Socket當中得到OutputStream

OutputStream outputStream=socket.getOutputStream();
bytebuffer[]=newbyte[4*1024];inttemp=0;

//將InputStream當中的數據取出,並寫入到OutputStream當中
while((temp=inputStream.read(buffer))!=-1)

5
{
outputStream.write(buffer,0,temp);}
outputStream.flush();}

TCP協議伺服器端實現:

//聲明一個ServerSocket對象
ServerSocketserverSocket=null;
try{

//創建一個ServerSocket對象,並讓這個Socket在4567埠監聽

serverSocket=newServerSocket(4567);

//調用ServerSocket的accept()方法,接受客戶端所發送的請求,
//如果客戶端沒有發送數據,那麼該線程就停滯不繼續

Socketsocket=serverSocket.accept();
//從Socket當中得到InputStream對象

InputStreaminputStream=socket.getInputStream();
bytebuffer[]=newbyte[1024*4];
inttemp=0;

//從InputStream當中讀取客戶端所發送的數據
while((temp=inputStream.read(buffer))!=-1)
{
System.out.println(newString(buffer,0,temp));}
}
catch(IOExceptione)
{

e.printStackTrace();}

serverSocket.close();
}

UDP方式
UDP的客戶端代碼實現如下:

public static void main(String[]args)
{
try{

//首先創建一個DatagramSocket對象

DatagramSocket socket=new DatagramSocket(4567);
//創建一個InetAddree

6

InetAddress serverAddress=InetAddress.getByName("192.168.1.104");

String str="hello";

//這是要傳輸的數據

byte data[]=str.getBytes();

//把傳輸內容分解成位元組

//創建一個DatagramPacket對象,並指定要講這個數據包發送到網
絡當中的哪個地址,以及埠號

DatagramPacket packet=new
DatagramPacket(data,data.length,serverAddress,4567);
//調用socket對象的send方法,發送數據
socket.send(packet);}
catch(Exceptione)
{

e.printStackTrace();}
}

UDP的服務端代碼實現如下:

//創建一個DatagramSocket對象,並指定監聽的埠號

DatagramSocket socket=new DatagramSocket(4567);
bytedata[]=newbyte[1024];
//創建一個空的DatagramPacket對象

DatagramPacket packet=new DatagramPacket(data,data.length);
//使用receive方法接收客戶端所發送的數據,
//如果客戶端沒有發送數據,該進程就停滯在這里

socket.receive(packet);

Stringresult=newString(packet.getData(),packet.getOffset(),
packet.getLength());

System.out.println("result--->"+result);

㈤ socket通信伺服器端怎麼寫

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.schele(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 indivial 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

㈥ Socket編程如何搭建一個外網可以訪問的伺服器

步驟:
1,和代理建立tcp聯接。
2,向代理發送版本的請求信息:
void CCommunicator::SendVer()
{
int datasize = 6;
char tempbuf[6];
tempbuf[0]=5;
tempbuf[1]=4;//標示後面所根的字接數
tempbuf[2]=0;
tempbuf[3]=1;
tempbuf[4]=2;
tempbuf[5]=3;
int senddatalen;
senddatalen=send(m_sock,(char*)tempbuf,6,0);
}
這一步如果失敗,斷開建立的tcp聯接,如果成功,如果需要用戶驗證則進行步驟3,否則進行4.
3,如果需要用戶驗證,則類似:
BOOL CCommunicator::SendUserTest()
{
int usernamelen=0;
int userpasslen=0;
usernamelen=m_strTestUserName.GetLength();
userpasslen=m_strTestUserPass.GetLength();
char tempbuf[100];
tempbuf[0]=5;
tempbuf[1]=usernamelen;//標示後面所根的字接數
strcpy(&tempbuf[2],m_strTestUserName);
tempbuf[2+usernamelen]=userpasslen;
strcpy((char*)&tempbuf [3+usernamelen],m_strTestUserPass);
int senddatalen;
int len;
len=usernamelen+userpasslen+3;
senddatalen=send(m_sock,(char*)tempbuf,len,0);
} 如果失敗,斷開建立的tcp聯接, 如果用戶返回成功,步驟4.
4,發送請求的協議類似:
void CCommunicator::SendRequestUDP()
{
int const datasize=10;
BYTE tempbuf[datasize]; tempbuf[0]=5;
tempbuf[1]=3;//標示UDP連接
tempbuf[2]=0;
tempbuf[3]=1;
tempbuf[4]=0;
tempbuf[5]=0;
tempbuf[6]=0;
tempbuf[7]=0;
*((SHORT*)(&(tempbuf[8])))=m_uBindUDPPort; //UDP在客戶端綁定的埠,就是你本地機器的做udp數據傳送的埠調用
//socket函數後,再調用bind()來邦定一個埠。
char temp;
temp=tempbuf[8];
tempbuf[8]=tempbuf[9];
tempbuf[9]=temp;
int senddatalen=send(m_sock,(char*)tempbuf,datasize,0);
}
如果失敗,斷開建立的tcp聯接,如果返回成功,驗證完畢!步驟5
5,真正的數據傳送,用代理傳送的時候,數據包的前面加上10個位元組類似:
void CCommunicator::CopyDataHead(BYTE * ptempbuf)
{
struct in_addr addr;
addr.s_addr=inet_addr(「202.220.33.333」);//這個ip是伺服器端的ip
ptempbuf[0]=0;
ptempbuf[1]=0;
ptempbuf[2]=0;
ptempbuf[3]=1;
ptempbuf[4]=(char)addr.S_un.S_un_b.s_b1;
ptempbuf[5]=(char)addr.S_un.S_un_b.s_b2;
ptempbuf[6]=(char)addr.S_un.S_un_b.s_b3;
ptempbuf[7]=(char)addr.S_un.S_un_b.s_b4;
*((SHORT*)(&(ptempbuf[8])))=m_uServerUDPPort;//伺服器的埠,就是你最終要發到那個伺服器的埠,也就是你的qq伺服器。
char temp;
temp=ptempbuf[8];
ptempbuf[8]=ptempbuf[9];
ptempbuf[9]=temp;
}
真正發送的時候類似:
int CCommunicator::SendBufferUDP(LPBYTE lpBuf,int nLen)
{
BYTE tempbuf[1000];
int iHeadData=0;
struct sockaddr_in her;
her.sin_family=AF_INET;
her.sin_addr.s_addr=inet_addr(m_szProxyAddr);//代理伺服器
her.sin_port=htons(m_uSocksPort);//發送請求的時候返回的代理伺服器端的埠,記住,這是最重要的。
CopyDataHead(tempbuf);
iHeadData=10;
nLen=nLen+10;
int addr_len;
addr_len=sizeof(struct sockaddr);
CopyMemory((char*)&tempbuf[iHeadData],lpBuf,nLen);
int returndatalen=sendto(m_socket,(char *)tempbuf,nLen,0,(struct sockaddr *)&her,addr_len);

php要讓伺服器使用socket要怎麼配置

socket伺服器的工作方式是這樣的,不間斷地運行以等待客戶端的連接。一旦客戶端連接上了,伺服器就會將它添加到客戶名單中,然後開始等待來自客戶端的消息。

下面是完整的源代碼:

// Set time limit to indefinite execution

set_time_limit (0);

// Set the ip and port we will listen on

$address = 'localhost';

$port = 10000;

$max_clients = 10;

// Array that will hold client information

$client = Array();

// Create a TCP Stream socket

$sock = socket_create(AF_INET, SOCK_STREAM, 0);

// Bind the socket to an address/port

socket_bind($sock, $address, $port) or die('Could not bind to address');

// Start listening for connections

socket_listen($sock);

echo "Waiting for connections... ";

// Loop continuously

while (true) {

// Setup clients listen socket for reading

$read[0] = $sock;

for ($i = 0; $i < $max_clients; $i++) {

if (isset($client[$i]['sock']))

$read[$i + 1] = $client[$i]['sock'];

}

// Set up a blocking call to socket_select()

if (socket_select($read, $write = NULL, $except = NULL, $tv_sec = 5) < 1)

continue;

/* if a new connection is being made add it to the client array */

if (in_array($sock, $read)) {

for ($i = 0; $i < $max_clients; $i++) {

if (empty($client[$i]['sock'])) {

$client[$i]['sock'] = socket_accept($sock);

echo "New client connected $i ";

break;

}

elseif ($i == $max_clients - 1)

echo "Too many clients... ";

}

} // end if in_array

// If a client is trying to write - handle it now

for ($i = 0; $i < $max_clients; $i++) { // for each client

if (isset($client[$i]['sock'])) {

if (in_array($client[$i]['sock'], $read)) {

$input = socket_read($client[$i]['sock'], 1024);

if ($input == null) {

echo "Client disconnecting $i ";

// Zero length string meaning disconnected

unset($client[$i]);

} else {

echo "New input received $i ";

// send it to the other clients

for ($j = 0; $j < $max_clients; $j++) {

if (isset($client[$j]['sock']) && $j != $i) {

echo "Writing '$input' to client $j ";

socket_write($client[$j]['sock'], $input, strlen($input));

}

}

if ($input == 'exit') {

// requested disconnect

socket_close($client[$i]['sock']);

}

}

} else {

echo "Client disconnected $i ";

// Close the socket

socket_close($client[$i]['sock']);

unset($client[$i]);

}

}

}

} // end while

// Close the master sockets

socket_close($sock);

可以先將它分解為幾個較小的部分。

  1. 第一部分是創建伺服器。Lines:2至20。

  2. 這部分代碼設置了變數、地址、埠、最大客戶端和客戶端數組。接下來創建socket並將其綁定到我們指定的地址和埠上。

  3. 下面我們要做的事情就是執行一個死循環(實際上我們是故意的!)。Lines:22至32。

  4. 在這部分代碼中我們做的第一步是設置 $read 數組。此數 組包含所有客戶端的套接字和我們主伺服器的套接字。這個變數稍後會用於select語句:告訴PHP監聽來自這些客戶端的每一條消息。

  5. socket_select()的最後一個參數告訴我們的伺服器在返回值之前最多等待5秒鍾。如果它的返回值小於1,那麼就表示沒有收到任何數據,所以只需要返回循環頂部,繼續等待。

腳本的下一個部分,是增加新的客戶端到數組中。Lines:33至44。

將新的客戶端放置在列表的末尾。檢查以確保客戶端的數量沒有超過我們想要伺服器處理的數量。

下面要介紹的代碼塊相當大,也是伺服器的主要部分。當客戶端將消息發送到伺服器時,就需要這塊代碼挺身而出來處理。消息可以是各種各樣的,斷開消息、實際斷開——只要是伺服器需要處理的消息。Lines:46至末尾。

代碼循環通過每個客戶端並檢查是否收到來自於它們的消息。如果是,獲取輸入的內容。根據輸入來檢查這是否是一個斷開消息,如果是那就從數組中刪除它們,反之,那它就是一個正常的消息,那我們的伺服器再次通過所有客戶端,並一個一個寫信息給他們,跳過發送者。

㈧ python怎樣建立socket伺服器

下面的例子是多線程實現的socket伺服器:

import socketimport threadingclass ThreadedServer(object):
def __init__(self, host, port):
self.host = host
self.port = port
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.sock.bind((self.host, self.port))

def listen(self):
self.sock.listen(5)
while True:
client, address = self.sock.accept()
client.settimeout(60)
threading.Thread(target = self.listenToClient,args = (client,address)).start()

def listenToClient(self, client, address):
size = 1024
while True:
try:
data = client.recv(size)
if data:
# Set the response to echo back the recieved data
response = data
client.send(response)
else:
raise error('Client disconnected')
except:
client.close()
return Falseif __name__ == "__main__":
while True:
port_num = input("Port? ")
try:
port_num = int(port_num)
break
except ValueError:
pass

ThreadedServer('',port_num).listen()

java問題:用socket編寫一個伺服器端程序

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

publicclass Server
{
private ServerSocket ss;

private Socket socket;

private BufferedReader in;

private PrintWriter out;

public Server()
{
try
{
ss = new ServerSocket(10000);
while (true)
{
socket = ss.accept();
String RemoteIP = socket.getInetAddress().getHostAddress();
String RemotePort = ":" + socket.getLocalPort();
System.out.println("A clientcome in!IP:" + RemoteIP
+ RemotePort);
in = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
String line = in.readLine();
System.out.println("Cleint sendis :" + line);
out = new PrintWriter(socket.getOutputStream(), true);
out.println("YourMessage Received!");
out.close();
in.close();
socket.close();
}
}
catch (IOException e)
{
out.println("wrong");
}
}

publicstaticvoid main(String[] args)
{
new Server();
}
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

publicclass Client {
Socket socket;

BufferedReader in;

PrintWriter out;

public Client()
{
try
{
System.out.println("Try toConnect to 127.0.0.1:10000");
socket = new Socket("127.0.0.1", 10000);
System.out.println("The ServerConnected!");
System.out.println("Pleaseenter some Character:");
BufferedReader line = new BufferedReader(new

InputStreamReader(System.in));
out = new PrintWriter(socket.getOutputStream(), true);
out.println(line.readLine());
in = new BufferedReader(new InputStreamReader(socket
.getInputStream()));
System.out.println(in.readLine());
out.close();
in.close();
socket.close();
}
catch (IOException e)
{
out.println("Wrong");
}
}

publicstaticvoid main(String[] args)
{
new Client();
}
}

你再改改代碼就可以了.但我沒時間幫你調了……

熱點內容
杉德卡卡號和密碼看哪裡 發布:2025-01-18 18:43:27 瀏覽:712
android返回退出 發布:2025-01-18 18:43:26 瀏覽:601
linux採集視頻 發布:2025-01-18 18:38:38 瀏覽:638
差異度演算法 發布:2025-01-18 18:34:27 瀏覽:698
電腦全套配置有哪些 發布:2025-01-18 18:32:39 瀏覽:145
新項目源碼 發布:2025-01-18 18:14:48 瀏覽:517
腳本設計圖 發布:2025-01-18 18:06:17 瀏覽:601
內部存儲空間不足總是跳出來 發布:2025-01-18 17:56:22 瀏覽:951
安卓光遇更新後魔法商店去哪裡了 發布:2025-01-18 17:55:47 瀏覽:133
安卓手機怎麼變成蘋果設備 發布:2025-01-18 17:46:06 瀏覽:916