java:创建一个TCP服务

来源:互联网 发布:人机交互与人工智能 编辑:程序博客网 时间:2024/05/16 10:03
import java.io.*;import java.net.*;//创建客户端,向服务端发送数据,并接收反馈信息class TCPClient{public static void main(String[] args)throws Exception{//创建Socket服务Socket s = new Socket("10.22.72.144", 20005);//获取Socket中的输出流OutputStream out = s.getOutputStream();out.write("hello Server".getBytes());//接受从服务端的反馈信息InputStream in = s.getInputStream();byte[] buf = new byte[1024];int len = in.read(buf);System.out.println(new String(buf, 0, len));s.close();}}//创建服务端class TCPServer{public static void main(String[] args) throws Exception{//创建ServerSocket服务ServerSocket ss = new ServerSocket(20005);//获取客户端对象Socket s = ss.accept();//获取客户端IPString ip = s.getInetAddress().getHostAddress();System.out.println(ip +"..connected..");//通过Socket客户端输入流获取客户端数据InputStream in = s.getInputStream();byte[] buf = new byte[1024];int len = in.read(buf);String str = new String(buf, 0, len);System.out.println(ip +":"+str);//向客户端发送反馈信息OutputStream out = s.getOutputStream();out.write("hello client".getBytes());ss.close();s.close();}}

0 0
原创粉丝点击