TCP发送数据
步骤
1.创建客服端的Socket对象(Socket)
2.获取输出流,写数据outputstream getOutputStream
3.释放资源void close
package Demo01Tcp;
import java.net.Socket;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
public class TcpClient {
public static void main(String[] args) throws IOException{
//1.创建一个客服端对象socket,构造方法中绑定服务器的ip地址和端口号
Socket socket=new Socket("127.0.0.1",99999);
//2.使用outputstream获取输出流对象
OutputStream os=socket.getOutputStream();
//3.使用write方法写数据
os.write("你好,服务器".getBytes());
//4.使用getinputstream获取输入流
InputStream is=socket.getInputStream();
//5.使用输入流的read方法获取从服务器发来的数据
byte[] bytes=new byte[1024];
int len=is.read();
System.out.println(new String(bytes,0,len));
//6.释放资源
socket.close();
}
}
TCP接受数据
1.创建服务器端的Socket对象(Serversocket)
2.监听客服端连接,读数据,并把数据显示在控制台InputStream getInputStream
3.释放资源void close**
package Demo01Tcp;
import java.net.ServerSocket;
import java.net.Socket;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class TcpServer {
public static void main(String[] args) throws IOException{
//1.创建服务器ServerSocket对象和系统要指定的端口号
ServerSocket server=new ServerSocket(99999);
//2.使用ServerSocket对象中的accpet方法,获取到请求的客服端对象
Socket socket=server.accept();
//3.使用socket对象中的getinputstream获取网络这农工输入对象
InputStream is=socket.getInputStream();
//4.使用网络输入流中read方法,读取客户端发送的数据
byte[] bytes=new byte[1024];
int len=is.read(bytes);
System.out.println(new String(bytes,0,len));
//5.使用socket对象中outputstream方法,获取输出流
OutputStream os=socket.getOutputStream();
//6.使用输出流中的write给客服端写数据
os.write("收到数据,谢谢".getBytes());
//7.释放资源
socket.close();
socket.close();
}
}