TCP通信程序练习(服务器给出反馈)
作者:互联网
package NetworkProgramming.TCP.SocketDemo01;
import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
/**
* FileName: CilentDemo
* Author: lps
* Date: 2022/4/1 22:17
* Sign:刘品水 Q:1944900433
*/
public class CilentDemo {
public static void main(String[] args) throws IOException {
//Socket(InetAddress address, int port)
//创建一个流套接字,并将其与指定的IP地址中的指定端口号连接起来。
Socket s = new Socket("192.168.10.102", 1944);
//OutputStream getOutputStream()
//返回此套接字的输出流。
OutputStream os = s.getOutputStream();
//BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// String line;
//while ((line= br.readLine())!=null){
// if ("886".equals(line)) {
// break;
// }
// os.write(line.getBytes(StandardCharsets.UTF_8));
os.write("我叫刘品水".getBytes(StandardCharsets.UTF_8));
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();
}
}
package NetworkProgramming.TCP.SocketDemo01;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
/**
* FileName: ServerDemo
* Author: lps
* Date: 2022/4/1 22:18
* Sign:刘品水 Q:1944900433
*/
public class ServerDemo {
public static void main(String[] args) throws IOException {
//ServerSocket(int port)
//创建一个服务器套接字,绑定到指定的端口。
ServerSocket ss = new ServerSocket(1944);
// while (true){
Socket s = ss.accept();
InputStream is = s.getInputStream();
byte[] bys = new byte[1024];
int len = is.read(bys);
//while ((len= is.read(bys))!=-1){
String data = new String(bys, 0, len);
System.out.println("服务器接受:" + data);
//}
// }
OutputStream os = s.getOutputStream();
os.write("数据已经收到".getBytes(StandardCharsets.UTF_8));
ss.close();
}
}
标签:java,String,import,反馈,TCP,bys,new,服务器,Socket 来源: https://www.cnblogs.com/lps1944900433/p/16089804.html