TCP通信程序的练习1

TCP通信程序的练习1

  • 客户端:发送数据,接收服务器反馈
    ClientDemo
package Demo;
/*

TCP通信程序的练习
    练习1:
    客户端:发送数据,接收服务器反馈
    服务器:接收数据,发送反馈
 */


import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

public class ClientDemo {
    public static void main(String[] args) throws IOException {
        //建立Socket对象
        Socket sgs = new Socket(InetAddress.getByName("sgs").getHostAddress(), 1110);

        //获取输出流,写数据,收到服务器反馈信息,释放资源
        OutputStream os = sgs.getOutputStream();
        os.write("时长两年半".getBytes());

        //收到服务器反馈信息
        InputStream is = sgs.getInputStream();
        byte[] bytes = new byte[1024];
        int len;
        while((len=is.read(bytes))!=-1){
            System.out.println("服务器:"+new String(bytes,0,len));
        }

        sgs.shutdownOutput();

        //释放资源
        sgs.close();
    }
}
  • 服务器:接收数据,发送反馈
    ServerDemo
package Demo;


import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerDemo {
    public static void main(String[] args) throws IOException {
        //建立ServerSocket对象
        ServerSocket ssk = new ServerSocket(1110);

        //通过accept()方法连接客户端
        Socket at = ssk.accept();

        //获取输入流,读数据,发出反馈,释放资源
        InputStream is = at.getInputStream();
        byte[] bytes = new byte[1024];
        int len=is.read(bytes);
            System.out.println(new String(bytes, 0, len));

        //发出反馈
        OutputStream oos = at.getOutputStream();
        oos.write("鸡你太美".getBytes());

        //释放资源
        ssk.close();
    }
}

输出的内容:
吴含
吴含

你可能感兴趣的:(tcp/ip,java,开发语言,网络协议,后端)