A. TCP伺服器和客戶機編程
伺服器(TCP/IP)編程實例
現在大多數語言都支持客戶-伺服器模式(C/S)編程,其中VB給我們提供了很好的客戶-伺服器編程方式。下面我們用VB來實現TCP/IP網路編程。
TCP/IP協議是Internet最重要的協議。VB提供了WinSock控制項,用於在TCP/IP的基礎上進行網路通信。當兩個應用程序使用Socket進行網路通信時,其中一個必須創建Socket伺服器偵聽,而另一個必須創建Socket客戶去連接伺服器。這樣兩個程序就可以進行通信了。
①創建伺服器
首先創建一個服務埠號。並開始偵聽是否有客戶請求連接。
建立一窗體,並向其增加一個Winsock控制項(可在工程菜單中的部件項來添加此控制項)
添加兩文本框Text1,Text2,和一按鈕Command1
Private Sub Form_Load()
SockServer.LocalPort = 2000 ′伺服器埠號,最好大於1000
SockServer.Listen ′開始偵聽
End Sub
Private Sub Form_Unload(Cancel As Integer)
SockServer.Close
End Sub
Private Sub SockServer_Close()
SockServer.Close
End Sub
Private Sub SockServer_ConnectionRequest(ByVal requestID As Long)
SockServer.Close
SockServer.Accept requestID ′表示客戶請求連接的ID號
End Sub
′當客戶向伺服器發送數據到達後,產生DataArrival事件,在事件中接收數據,GetData方法接收數據。
Private Sub SockServer_Data
Arrival(ByVal bytesTotal As Long)
Dim s As String
SockServer.GetData s
Text1.Text = s
End Sub
當需要向客戶發送數據時,只需調用SendData方法。
Private Sub Command1_Click()
SockServer .SendData Text2.Text
End Sub
②創建客戶
要創建客戶連接伺服器,首先設置伺服器主機名,如IP地址、域名或計算機名,然後設置伺服器埠,最後連接伺服器。
建立一窗體,並向其增加一個Winsock控制項(可在工程菜單中的部件項來添加此控制項),取名為:SockC1。添加兩文本框Text1,Text2,和一按鈕Command1
Private Sub Form_Load()
SockCl.RemoteHost =′127.0.0.1″
′表示伺服器主機名
SockCl.RemotePort = 2000
′表示伺服器埠名
SockCl.Connect
′連接到伺服器
End Sub
Private Sub Form_Unload(Cancel As Integer)
SockCl.Close
End Sub
Private Sub SockCl_Close()
SockCl.Close
End Sub
Private Sub SockCl_DataArrival(ByVal bytesTotal As Long)
Dim s As String
SockCl.GetData s ′接收數據到文本框中
Text1.Text = s
End Sub
Private Sub Command1_Click()
SockCl.SendData Text2.Text ′向伺服器發送數據
End Sub
③進行通信
把這兩個窗體分別編譯成兩個EXE文件,伺服器Server.exe和客戶Client.exe程序,並把它們分別安裝在伺服器端和客戶端,這樣就可以實現兩者通信了。
-
B. java網路編程應該怎樣在客戶端和伺服器間實現通信
以前寫的,照貼了。。。伺服器端:import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.*;
import java.net.*;/*6、 採用UDP協議,編寫一個Java網路應用程序,該應用分伺服器端程序和客戶端程序兩部分。
* 客戶端指定一個伺服器上的文件名,讓伺服器發回該文件的內容,或者提示文件不存在。
* (20分)(服務端程序和客戶端程序分別命名為Server.java和Client.java)*/
public class N4BT6 extends Frame
{
DatagramSocket socket ;
DatagramPacket packet ;byte[] buf ;
File file ;
FileInputStream input;
String message = "該文件不存在";
TextArea text;
public N4BT6(String title)
{
super(title);
text = new TextArea(6,4);
add(text);
setSize(400, 300);
setVisible(true);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
dispose();
}
});
buf = new byte[1024];
try
{
socket = new DatagramSocket(1230);
packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
file = new File(new String(packet.getData()));
socket = new DatagramSocket();
}
catch (Exception e)
{e.printStackTrace();
}
if(file.exists())
{
try
{
buf = new byte[(int)file.length()];
packet = new DatagramPacket(buf,buf.length,InetAddress.getLocalHost(),1234);
input = new FileInputStream(file);
input.read(buf);
socket.send(packet);
}
catch (IOException e)
{
e.printStackTrace();
}
}
else
{
try
{
packet = new DatagramPacket(message.getBytes(),message.getBytes().length,
InetAddress.getLocalHost(),1234);
socket.send(packet);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
public static void main(String[] args)
{
new N4BT6("Server");
}
}
客戶端:import java.awt.*;
import java.awt.event.*;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;public class N4BT6_2 extends Frame
{
TextArea text;
String message = "Q.txt";
DatagramSocket socket ;
DatagramPacket packet;
byte[] buf;
public N4BT6_2(String title)
{
super(title);
text = new TextArea(6,4);
add(text);
setSize(400, 300);
setVisible(true);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
dispose();
}
});
try
{
socket = new DatagramSocket();
packet = new DatagramPacket(message.getBytes(),message.getBytes().length,
InetAddress.getLocalHost(),1230);
socket.send(packet);
}
catch (Exception e)
{
e.printStackTrace();
}
try
{
buf = new byte[1024];
socket = new DatagramSocket(1234);
packet = new DatagramPacket(buf,buf.length);
socket.receive(packet);
text.append(new String(buf));
}
catch (Exception e)
{
e.printStackTrace();
}
}
public static void main(String[] args)
{
new N4BT6_2("Client");
}
}
C. 用C語言編寫伺服器端和客戶機端的關鍵部分代碼!
//服務端 C++
#include "stdafx.h"
#include "stdio.h"
#include "winsock2.h"
#include <vector>
using std::vector;
SOCKET s;
vector<SOCKET> cc;
void onAccept()
{
sockaddr_in sa;
int add_len = sizeof(sa);
SOCKET c = accept(s,(sockaddr*)&sa,&add_len);
if(c!=INVALID_SOCKET)
{
printf("client:%s port:%d connected!\n",inet_ntoa(sa.sin_addr),sa.sin_port);
send(c,"hello",5,0);
cc.push_back(c);
}
else
{
printf("invalid connect\n");
}
}
void onRecv(const fd_set &fs)
{
for(int i=0;i<cc.size();++i)
{
if(FD_ISSET(cc[i],&fs))
{
char buffer[256]={0};
int rc= recv(cc[i],buffer,255,0);
if(rc>0)
{
printf("recv msg:%s\n",buffer);
send(cc[i],buffer,strlen(buffer)+1,0);
}
else if(rc == SOCKET_ERROR)
{
printf("recv msg failed:%d\n",::WSAGetLastError());
closesocket(cc[i]);
cc.erase(cc.begin()+i);
break;
}
}
}
}
int main(int argc, char* argv[])
{
//init
WORD wVersionRequested;
WSADATA wsaData;
wVersionRequested = MAKEWORD( 2, 2 );
WSAStartup( wVersionRequested, &wsaData );
s = socket(AF_INET,SOCK_STREAM,0);
if(s!=INVALID_SOCKET)
{
printf("create socket success!\n");
}
{
sockaddr_in sa;
sa.sin_family = AF_INET;
sa.sin_port = htons( 1500 );
sa.sin_addr.s_addr = 0 ; //*²»Ö¸¶¨µØÖ·
int rc = bind(s,(sockaddr *)&sa,sizeof(sa));
if(rc == SOCKET_ERROR)
{
printf("bind failed:%d\n",::WSAGetLastError());
return -1;
}
}
listen(s,SOMAXCONN);
timeval timeout={0,100};
while(true)
{
fd_set fs;
FD_ZERO(&fs);
FD_SET(s,&fs);
int rc = select(0,&fs,0,0,&timeout);
if(rc>0)
{
onAccept();
}
else if(rc == 0)
{
//printf("no connect!\n");
}
else
{
printf("select1 error:%d\n",::WSAGetLastError());
}
if(cc.size()>0)
{
FD_ZERO(&fs);
for(int i=0;i<cc.size();++i)
{
FD_SET(cc[i],&fs);
}
rc = select(0,&fs,0,0,&timeout);
if(rc>0)
{
onRecv(fs);
}
else if(rc == 0)
{
//printf("no recv!\n");
}
else
{
printf("select2 error:%d\n",::WSAGetLastError());
}
}
}
closesocket(s);
//clean
WSACleanup( );
return 1;
}
//=====================[client]====================
#include "stdafx.h"
#include <stdio.h>
#include <winsock2.h>
#include <windows.h>
#include <process.h>
SOCKET c;
unsigned int __stdcall myrecv(void *)
{
while(true)
{
char recv_buffer[256]={0};
int rc =recv(c,recv_buffer,255,0)>0;
if(rc>0)
{
printf("recv:%s\n",recv_buffer);
}
else if(rc==SOCKET_ERROR)
{
printf("recv failed:%d\n",::WSAGetLastError());
break;
}
}
_endthreadex(0);
return 0;
}
int main(int argc, char* argv[])
{
//init
WORD wVersionRequested;
WSADATA wsaData;
wVersionRequested = MAKEWORD( 2, 2 );
WSAStartup( wVersionRequested, &wsaData );
c = socket(AF_INET,SOCK_STREAM,0);
if(c!=INVALID_SOCKET)
{
printf("create socket success!\n");
}
//connect
{
sockaddr_in sa;
sa.sin_family = AF_INET;
sa.sin_port = htons( 1500 );
sa.sin_addr.s_addr = inet_addr("127.0.0.1") ; //*²»Ö¸¶¨µØÖ·
int rc = connect(c,(sockaddr *)&sa,sizeof(sa));
if(rc == SOCKET_ERROR)
{
printf("connect failed:%d\n",::WSAGetLastError());
return -1;
}
}
_beginthreadex(0,0,&myrecv,0,0,0);
int count = 0;
timeval timeout={0,100};
while(true)
{
char send_buffer[256]={0};
sprintf(send_buffer,"s%d",count++);
int rc = send(c,send_buffer,strlen(send_buffer),0);
if(rc>0)
{
printf("send:%s\n",send_buffer);
}
else if(rc==SOCKET_ERROR)
{
printf("send failed:%d\n",::WSAGetLastError());
break;
}
}
closesocket(c);
//clean
WSACleanup( );
return 0;
}