更多精彩内容,请见:http://www.16boke.com
by zxy,QQ群:168424095
由于数据类型的关系搞了两天才出来,不过还是很高兴.
C++代码:
#include "stdio.h"
#include <WINSOCK2.H>
#pragma comment(lib, "Ws2_32.lib")
#define MSG_LENGTH 1024 //数组的长度
int main(int argc, char* argv[])
{
WSADATA m_WSADATA;
char buf[MSG_LENGTH];
int m_nRecvBytes,m_nSendBytes;
SOCKET Listening;
SOCKET NewConnection;
SOCKADDR_IN ServerAddr;
SOCKADDR_IN ClientAddr;
int ClientAddrLen=sizeof(ClientAddr);
int m_nPort = 5000;
WSAStartup(MAKEWORD(2,2),&m_WSADATA);
Listening = socket( AF_INET, SOCK_STREAM, IPPROTO_TCP );
ServerAddr.sin_family = AF_INET;
ServerAddr.sin_addr.s_addr = htonl(INADDR_ANY);
ServerAddr.sin_port = htons(m_nPort);
bind(Listening,(SOCKADDR *)&ServerAddr,sizeof(ServerAddr));/*绑定一个IP地址和一个特定的端口号*/
listen(Listening,5);/*使流套接字处于监听状态*/
printf("Wating accpet....\n");
while(true){
/*从处于监听状态的流套接字的客户连接请求队列中取出排在最前的一个客户请求,
并且创建一个新的套接字来与客户套接字创建连接通道*/
//创建一个能够进行网络通信的套接字
NewConnection = accept(Listening,(SOCKADDR *)&ClientAddr,&ClientAddrLen);
printf( "Wating recv.....\n" );
/*从TCP连接的另一端接收数据*/
if((m_nRecvBytes=recv(NewConnection,buf,MSG_LENGTH,0)) == SOCKET_ERROR )
{
printf( "\nErrorcode=%d, Recv from client\n", WSAGetLastError() );
return 0;
}
buf[m_nRecvBytes]='\0';
printf("Receive:%s\n",buf);
scanf("%s",buf);
buf[strlen(buf)]='\0';
/*向TCP连接的另一端发送数据。*/
if((m_nSendBytes = send(NewConnection,buf, static_cast<int>(strlen(buf)),0)) == SOCKET_ERROR)
{
printf("Send:%s\n",buf);
break;
}
printf("Send:%s\n",buf);
}
/* 应用程序在完成对请求的Socket库的使用后,要调用WSACleanup函数来解除与
Socket库的绑定并且释放Socket库所占用的系统资源。*/
WSACleanup();
return 0;
}
java代码:
import java.net.*;
import java.io.*;
public class Client {
public static void main(String[] args) {
try {
int index = 0;
byte[] receive = new byte[28];
while(true){
Socket sock = new Socket("127.0.0.1", 5000);
BufferedReader buf;
String str;
buf=new BufferedReader(new InputStreamReader(System.in));
str=buf.readLine();
System.out.println("send content:" + str);
sock.getOutputStream().write(str.getBytes());
sock.getInputStream().read(receive);
str = new String(receive);
System.out.println("response: " + str);
sock.close();
}
}catch (Exception e) {
e.printStackTrace();
}
}
}
更多精彩内容,请见:http://www.16boke.com