1、服务器端
import javaioDataOutputStream;import javaioIOException;
import javanetServerSocket;
import javanetSocket;
public class SocketServer {
private static final int PORT = 8088;
public static void main(String[] args) {
ServerSocket server = null;
try {
server = new ServerSocket(PORT);
while (true) {
Socket client = serveraccept();
new Thread(new Server(client))start();
}
} catch (IOException e) {
eprintStackTrace();
}
}
}
class Server implements Runnable {
private Socket client;
public Server(Socket client) {
thisclient = client;
}
public void run() {
DataOutputStream output = null;
try {
output = new DataOutputStream(clientgetOutputStream());
outputwriteUTF("你好我是服务器");
} catch (IOException e) {
eprintStackTrace();
} finally {
try {
if (output != null) outputclose();
output = null;
} catch (IOException e) {}
}
}
}
2、客户端
import javaioDataInputStream;import javaioIOException;
import javanetSocket;
import javanetUnknownHostException;
public class Client extends Socket {
private static final int PORT = 8088;
public static void main(String[] args) {
Socket socket = null;
try {
socket = new Socket("127001", PORT);
DataInputStream in = new DataInputStream(socketgetInputStream());
String res = inreadUTF();
Systemoutprintln(res);
if (in != null) inclose();
} catch (UnknownHostException e) {
eprintStackTrace();
} catch (IOException e) {
eprintStackTrace();
} finally {
if (socket != null) {
try {
socketclose();
} catch (IOException e) {}
}
}
}
}
C++ TCP客户端代码写法:
客户端编程的步骤:
1:加载套接字库,创建套接字(WSAStartup()/socket());
2:向服务器发出连接请求(connect());
3:和服务器端进行通信(send()/recv());
4:关闭套接字,关闭加载的套接字库(closesocket()/WSACleanup())。
代码:
#include <stdioh>#include <Winsock2h>
#pragma comment(lib,"WS2_32lib")
void main()
{
WORD wVersionRequested;
WSADATA wsaData;
int err;
wVersionRequested = MAKEWORD(1,1);
err = WSAStartup(wVersionRequested,&wsaData);
if (err !=0)
{
return;
}
if (LOBYTE(wsaDatawVersion) != 1||
HIBYTE( wsaDatawVersion ) != 1 )
{
WSACleanup();
return;
}
SOCKET sockSrv = socket(AF_INET,SOCK_STREAM,0);
SOCKADDR_IN addrSrv;
addrSrvsin_addrS_unS_addr=htonl(INADDR_ANY);
addrSrvsin_family=AF_INET;
addrSrvsin_port=htons(6000);
bind(sockSrv,(SOCKADDR)&addrSrv,sizeof(SOCKADDR));
listen(sockSrv,5);
SOCKADDR_IN addrClient;
int len=sizeof(SOCKADDR);
while(1)
{
SOCKET sockConn=accept(sockSrv,(SOCKADDR)&addrClient,&len);
char sendBuf[50];
sprintf(sendBuf,"Welcome %s to here!",inet_ntoa(addrClientsin_addr));
send(sockConn,sendBuf,strlen(sendBuf)+1,0);
char recvBuf[50];
recv(sockConn,recvBuf,50,0);
printf("%s\n",recvBuf);
closesocket(sockConn);
}
}
以上就是关于编写一个简单的TCP通信程序。服务器发送“你好我是服务器”,客户端接收该信息并显示在屏幕上。用Java写全部的内容,包括:编写一个简单的TCP通信程序。服务器发送“你好我是服务器”,客户端接收该信息并显示在屏幕上。用Java写、C++ TCP客户端代码怎么写、等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)