背景
Java实现TCP协议发送/接收数据。
实现
注:
- TCP协议需要三次握手以及四次挥手,因此在执行时需要先在Server端侦听端口。否则无法建立Client端与Server端的链接。
Client端
package itheima2;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
public class ClientDemo {
public static void main(String[] args) throws IOException {
Socket s = new Socket("10.2.120.65",10000);
OutputStream os = s.getOutputStream();
os.write("Hello,World! TCP!".getBytes());
s.close();
}
}
Server端
package itheima2;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class ServerDemo {
public static void main(String[] args) throws IOException {
ServerSocket ss = new ServerSocket(10000);
Socket s = ss.accept();
InputStream is = s.getInputStream();
byte[] bys = new byte[1024];
int len = is.read(bys);
String data = new String(bys, 0, len);
System.out.println("数据是:" + data);
ss.close();
}
}
|