【Java】TCP发送与接收数据
发送
package LearnJava17;
import java.io.IOException;
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 s=new Socket(InetAddress.getByName("127.0.0.1"),10000);
Socket s = new Socket("127.0.0.1",10000);
// 获取输出流,写数据
OutputStream os = s.getOutputStream();
os.write("Hello,TCP".getBytes());
// 释放资源
s.close();
}
}
接收
package LearnJava17;
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);
// 释放资源
s.close();
ss.close();
}
}
本文来自博客园,作者:木子欢儿,转载请注明原文链接:https://www.cnblogs.com/HGNET/p/16208024.html