package TCP;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class Demo {
/**
* TCP协议的网络编程
* 服务器
*/
public static void main(String[] args) throws IOException {
//搭建服务器
ServerSocket server = new ServerSocket(55565);
System.out.println("服务器启动完毕");
//等待客户端的连接
Socket socket = server.accept();//程序在这里等待,直到接收到客户端的连接
System.out.println("一个客户端连接了");
//服务器向客户端发消息
OutputStream os = socket.getOutputStream();
PrintStream ps = new PrintStream(os);//转为打印流
ps.println("欢迎你连接服务器");
/**
* InputStream接收消息
* OutputStream发消息
*/
//服务器接收客户端消息
InputStream is = socket.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));//转为读取流
String text = br.readLine();
System.out.println("服务器接收到客户端的回复:"+text);
System.out.println("服务器程序执行结束");
}
}
客户端
package TCP;
import java.io.*;
import java.net.Socket;
public class ClicetDemo {
//客户端
public static void main(String[] args) throws IOException {
Socket socket = new Socket("127.0.0.1",55565);//new一个socket,IP地址,端口号
InputStream is = socket.getInputStream();//获取传过来的数据
BufferedReader br = new BufferedReader(new InputStreamReader(is));//转为字符读取流
String text = br.readLine();
System.out.println("客户端接到消息:"+text);
OutputStream os = socket.getOutputStream();
PrintStream ps = new PrintStream(os);
ps.println("服务器你好");
}
}