前言
关于java基于TCP协议实现两台主机间的通信,主要使用套接字Socket和ServerSocket类,Socket类用于实现客户端套接字,套接字是主机间通信的端点,其主要方法如下:
//创建一个流套接字,并指定地址和端口@b@public Socket(String host, int port) throws UnknownHostException, IOException@b@//返回当前套接字远程连接IP地址@b@public InetAddress getInetAddress()@b@//返回将字节写入此套接字的输入流@b@ public OutputStream getOutputStream() throws IOException@b@//返回从套接字读取字节的输入流@b@public InputStream getInputStream() throws IOException@b@//关闭套接字,并关闭此套接字关联通道
服务端套接字ServerSocket类,提供TCP服务。服务端套接字可以接收客户端的接入请求,然后给客户端发送相应消息。ServerSocket类的主要使用方法如下:
//创建绑定到特定端口的服务器套接字@b@public ServerSocket(int port) throws IOException @b@//监听此套接字连接,此方法在连接之前一直阻塞@b@public Socket accept() throws IOException@b@//关闭此套接字,与此套接字的关联通道将关闭@b@public void close() throws IOException
代码示例
服务端测试代码
import java.io.BufferedReader;@b@import java.io.IOException;@b@import java.io.InputStreamReader;@b@import java.net.ServerSocket;@b@import java.net.Socket;@b@@b@public class Server {@b@@b@ public static void main(String[] args) {@b@ ServerSocket server;@b@ try {@b@ server=new ServerSocket(8888);@b@ Socket s=server.accept();@b@ @b@ BufferedReader br=new BufferedReader(new InputStreamReader(s.getInputStream()));@b@ System.out.println("服务端接收消息:"+br.readLine());@b@ br.close();@b@ server.close();@b@ } catch (IOException e) {@b@ // TODO Auto-generated catch block@b@ e.printStackTrace();@b@ }@b@ }@b@@b@}
客户端连接代码
import java.io.IOException;@b@import java.io.PrintStream;@b@import java.net.Socket;@b@import java.net.UnknownHostException;@b@@b@public class Client {@b@@b@ public static void main(String[] args) {@b@ Socket client;@b@ PrintStream ps;@b@ try {@b@ client=new Socket("127.0.0.1",8888);@b@ System.out.println("连接Success!");@b@ ps=new PrintStream(client.getOutputStream());@b@ ps.println("小木人印象");@b@ client.close();@b@ } catch (UnknownHostException e) {@b@ // TODO Auto-generated catch block@b@ e.printStackTrace();@b@ } catch (IOException e) {@b@ // TODO Auto-generated catch block@b@ e.printStackTrace();@b@ }@b@ }@b@}
运行结果:
服务端接收消息:小木人印象