Java的TCP/IP编程学习--简单的TCP/IP应用程序和回馈服务器
一、简单的TCP服务器
指定ServerSocket 本地(localhost或者127.0.0.1或者其他)端口(8888或其他),接收端口请求。循环等待客户端Socket连接。读取客户端发送的数据并写回客户端Socket,让客户端接收
package main;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;
/**
* @ClassName TCPEchoServer
* @Description TODO
* @Author Cays
* @Date 2019/3/15 11:01
* @Version 1.0
**/
public class TCPEchoServer {
private static final int BUFSIZE=32;//size of receive buffer
public static void main(String[] args) throws IOException {
//指定本地端口
int servPort=8888;
//创建服务器端套接字,监听特定端口的客户端请求
ServerSocket serverSocket=new ServerSocket(servPort);
//size of received message
int recvMsgSize;
//要接受的字符的缓冲区
byte []receiveBuf=new byte[BUFSIZE];
//永久循环,迭代处理新的连接
while (true){
//阻塞等待,直到有向serverSocket监听端口新的连接请求
Socket clntSock=serverSocket.accept();
SocketAddress clientAddress=clntSock.getRemoteSocketAddress();
//输出客户端地址/端口号
System.out.println("Handling client at "+clientAddress);
InputStream in=clntSock.getInputStream();
OutputStream out=clntSock.getOutputStream();
//receive until client closes connectoion,
while ((recvMsgSize=in.read(receiveBuf))!=-1){
out.write(receiveBuf,0,recvMsgSize);
}
//close the socket. we are done with this client
clntSock.close();
}
//not reached
}
}
二、简单的TCP应用程序
连接本地服务器IP/端口,并发送简单字符串,接收服务器的回馈消息并显示
package main;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.SocketException;
/**
* @ClassName TCPEchoClient
* @Description TODO
* @Author Cays
* @Date 2019/3/15 10:08
* @Version 1.0
**/
public class TCPEchoClient {
public static void main(String []args) throws IOException {
//Server name or IP address
String server="127.0.0.1";
//Convert argument String to bytes using the default character encoding
//转换回馈字符串
byte []data="Hello World!".getBytes();
//确定回馈服务器的端口号8888
int servPort=8888;
//Create socket that is connected to server on specified port
//创建服务器套接字,连接到由名字/ip指定的服务器
Socket socket=new Socket(server,servPort);
System.out.println("Connected to server...encoding echo string");
//获取网络套接字的输入/输出流,通过将字节写入套接字的OutputStream
//发送数据,通过InputStream读取数据
InputStream in=socket.getInputStream();
OutputStream out=socket.getOutputStream();
out.write(data);//send the encoding string to the server
//receive the same string back from the server
int totalBytesRcvd=0;//total bytes received so far
int bytesRcvd;//bytes received in last read
//接收服务器数据
while (totalBytesRcvd<data.length){
if ((bytesRcvd=in.read(data,totalBytesRcvd,data.length-totalBytesRcvd))==-1){
throw new SocketException("Connection closed prematurely");
}
totalBytesRcvd+=bytesRcvd;
}
//data array is full
//打印接收的字符串
System.out.println("Received:"+(new String(data)));
socket.close();
}
}