TCP发送接收数据2
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了TCP发送接收数据2相关的知识,希望对你有一定的参考价值。
//客户端package liu.net.tcp;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client3 {
public static void main(String[] args) throws UnknownHostException, IOException {
System.out.println("客户端启动。。。。");
//发数据给服务端
Socket s = new Socket("127.0.0.1",8899);
OutputStream out = s.getOutputStream();
out.write("client send data to server".getBytes());
//接收服务端的数据
InputStream in = s.getInputStream();
byte[] buf = new byte[1024];
int len = in.read(buf);
String data = new String(buf,0,len);
System.out.println("从服务端收到的数据:"+data);
s.close();
}
}
//服务器端
package liu.net.tcp;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Server3 {
public static void main(String[] args) throws IOException {
/* 客户端发送数据给服务端
* 服务端收到数据后发信息给客户端
*/
System.out.println("服务端启动。。。。");
//接收客户端发来的数据
ServerSocket ss = new ServerSocket(8899);
Socket s = ss.accept();
byte[] buf = new byte[1024];
InputStream in = s.getInputStream();
int len = in.read(buf);
String data = new String(buf,0,len);
System.out.println("服务端收到的数据:"+data);
//发数据给客户端
String dataToClient = "11111";
OutputStream out = s.getOutputStream();
out.write(dataToClient.getBytes());
s.close();
ss.close();
}
}
以上是关于TCP发送接收数据2的主要内容,如果未能解决你的问题,请参考以下文章