[Java网络编程基础]TCP发送和接收数据
Posted Wecccccccc
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Java网络编程基础]TCP发送和接收数据相关的知识,希望对你有一定的参考价值。
代码如下:
package ClientPack;
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("192.168.1.123"),10000);
Socket s = new Socket("192.168.1.123",12345);
OutputStream os = s.getOutputStream();
os.write("hello,tcp,我来了".getBytes());
s.close();
}
}
代码如下:
package ClientPack;
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(12345);
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();
}
}
以上是关于[Java网络编程基础]TCP发送和接收数据的主要内容,如果未能解决你的问题,请参考以下文章