[这个贴子最后由huym在 2003/07/08 03:10pm 第 2 次编辑]
下面程序进行java客户端程序与vc服务器端程序进行数据包交换的例子,
本例只将数据包的长度传给服务器端,大家如果有用,可以进行改进。
java的客户端程序
////HuymClient.java
//
import java.net.*;
import java.io.*;
import java.lang.*;
public class HuymClient{
public static void main(String args[]){
Socket socket;
InputStream Is;
OutputStream Os;
DataInputStream DIS;
PrintStream PS;
try{
//向主机名为args[0]的服务器申请连接
socket=new Socket("localhost",7777);
System.out.println("ok");
System.out.println("****");
System.out.println("");
//获得对应socket的输入/输出流
Is=socket.getInputStream();
Os=socket.getOutputStream();
//建立数据流
DIS=new DataInputStream(Is);
PS=new PrintStream(Os);
DataInputStream in=new DataInputStream(System.in);
byte[] bytebuf=IntToByte(246893);
PS.write(bytebuf,0,4);
//关闭连接
DIS.close(); //关闭数据输入流
PS.close(); //关闭数据输出流
Is.close(); //关闭输入流
Os.close(); //关闭输出流
socket.close(); //关闭socket
}
catch(Exception e){
System.out.println("Error:"+e);
}
}
public static byte[] IntToByte(int nValue) {
int nTemp=0;
byte[] bytebuf=new byte[4];
for(int i=0;i<4;i++){
nTemp=nValue>>(i*8);
Integer IntObj=new Integer(nTemp);
bytebuf[i]=IntObj.byteValue();
System.out.println(bytebuf[i]);
}
return bytebuf;
}
public static int ByteToInt(byte[] bytebuf){
byte[] buf=new byte[4];
int len=4,i=0;
int nTemp=0,nValue=0;
if(bytebuf.length<len){
len=bytebuf.length;
}
if(len==0){
return -1;
}
for(i=0;i<len;i++){
buf[i]=bytebuf[i];
}
for(i=0;i<4;i++){
nTemp=(int)buf[i];
if(nTemp<0){
nTemp=256+nTemp;
}
System.out.println(nTemp);
nTemp=nTemp<<(8*i);
nValue=nValue+nTemp;
}
return nValue;
}
}
服务器端c程序
////Server.c
//
#include <windows.h>
#include <stdio.h>
int main(int argc, char* argv[])
{
//Initialise the winsock 2 stack
WSADATA wsa;
int sock_fd=0;
int nRet=0;
SOCKADDR_IN addr;
char buffer[1024];
struct sockaddr conn_addr;
int conn_addr_len=0;
SOCKET sock;
int len=0;
int errno;
char* stopstring;
if ( WSAStartup(MAKEWORD(1, 1), &wsa) != 0 )
{
return -1;
}
if ( (sock_fd=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP)) == INVALID_SOCKET)
{
return -1;
}
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_ANY);
addr.sin_port = htons(7777);
if (bind(sock_fd,(struct sockaddr FAR *)&addr,sizeof(addr)) == SOCKET_ERROR)
{
printf("err/n");
}
if (listen(sock_fd,5) < 0)
{
printf("err/n");
}
memset((char*)&conn_addr,0,sizeof(conn_addr));
conn_addr_len=sizeof(conn_addr);
fprintf(stdout,"wait your message.../n");
sock = accept(sock_fd,&conn_addr,(int FAR *)&conn_addr_len);
errno=GetLastError();
memset(buffer,0,1024);
recv(sock,buffer,1024,0);
fprintf(stdout,"%s/n",buffer);
memcpy((char*)&len,buffer,4);
fprintf(stdout,"%d/n",len);
fprintf(stdout,"%X/n",len);
closesocket(sock);
closesocket(sock_fd);
WSACleanup();
return 0;
}