今晚上开始研究java的网络编程,先从socket开始吧。
java为TCP协议提供了两个类:Socket和Socketserver。一个Socket实例代表了TCP的一端,一个TCP连接是一条抽象的双向信道,两端分别由IP地址和端口号确定。在开始通信前,要建立一个TCP连接,需要先由客户端TCP向服务端TCP发送连接请求。ServerSocket实例则监听TCP连接请求,并为每个请求创建新的Socket实例。
下面是一个简单的client/server的例子:
客户端代码:
//1.创建一个Socket实例,构造方法制定远程主机和端口建立一个TCP连接。
//2.通过套接字的输入输出流(I/O)进行通信,一个Socker连接实例包括InputStream和OutStream
//3.使用Socket类的close()方法关闭连接
public class TCPECHOClient {
public static void main(String[] args) {
String server = "localhost";
String data = "Echo this!";
byte[] bs = data.getBytes();
try {
//创建一个套接字,并连接到由名字或IP地址指定的服务器
Socket socket = new Socket(server,80);
System.out.println("Connecting to server……");
//获取输入输出流
InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream();
//发送字符串到回馈服务器
out.write(bs);
//接收回馈信息
int totalDateRecived = 0;
int bytesRecvd = 0 ;
while(totalDateRecived<bs.length){
totalDateRecived +=bytesRecvd;
if((bytesRecvd=in.read(bs,totalDateRecived,bs.length-totalDateRecived))==-1)
throw new SocketException("connection closed!");
}
System.out.println("received:"+new String(bs));
socket.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
服务端:
public class TCPEchoServer {
private static int BUFSiZE = 32;
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(80);
int received = 0;
byte[] receiveBuf = new byte[BUFSiZE];
while(true){
Socket socket = serverSocket.accept();
//返回一个包含了客户端地址和端口号的InetSocketAddress实例
SocketAddress clientAddress = socket.getRemoteSocketAddress();
System.out.println("handling client at:"+clientAddress);
InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream();
while((received=in.read(receiveBuf))!=-1){
out.write(receiveBuf,0,received);
}
socket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
输出结果:
客户端:Connecting to server……
received:Echo this!
服务端:handling client at:/127.0.0.1:50884