public class TCPrecevierDemo {
public static void main(String[] args) throws IOException {
//创建服务器端套接字对象
ServerSocket ss = new ServerSocket(10045);
//监听客户端连接,获取一个对应的套接字对象
Socket s = ss.accept();
//获取输入流对象,读数据
InputStream is = s.getInputStream();
byte[] bys=new byte[1024];
int len = is.read(bys); //未读到前阻塞
String comment = new String(bys,0,len);
String ip = s.getInetAddress().getHostAddress();
System.out.println(ip+"发来了:"+comment);
//服务器给客户端发回一个反馈信息
OutputStream os = s.getOutputStream();
os.write("数据已收到".getBytes());
//释放资源
s.close();
ss.close();
}
}
public class TcpsendDemo {
public static void main(String[] args) throws IOException {
//创建Tcp发送端套接字对象
Socket s = new Socket("192.168.42.194", 10045);
//获取输出流,并写数据
OutputStream os = s.getOutputStream();
os.write("hello,TCP,我来了!".getBytes());
//获取输入流,得到反馈信息
InputStream is = s.getInputStream();
byte[] bys = new byte[1024];
int len = is.read(bys); //未读到前阻塞
String respond = new String(bys, 0, len);
System.out.println("Client: "+ respond);
//释放资源
s.close();
}
}