简单的控制台聊天(TCP)


import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;

//TCP通信客户端
public class TCPClient {

public static Scanner scanner=new Scanner(System.in);
public static void main(String[] args) throws IOException {
Socket socket=new Socket("127.0.0.1",8888);
System.out.println("到达客户端。。。");
OutputStream os = socket.getOutputStream();
os.write("服务器是你吗?".getBytes());

while (true){
InputStream is = socket.getInputStream();
byte[] bytes =new byte[1024];
int len = is.read(bytes);
System.out.println("服务器:"+new String(bytes,0,len));
String cilent = scanner.nextLine();
os.write(cilent.getBytes());

//关闭流,释放资源
// os.close();
}
}
}









import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

//TCP通信服务端
public class TCPServer {
public static Scanner scanner = new Scanner(System.in);

public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket(8888);
Socket socket = server.accept();
System.out.println("启动服务。。。");
while (true){
InputStream is = socket.getInputStream();
byte[] bytes = new byte[1024];
int len = is.read(bytes);
System.out.println("客户端: "+new String(bytes, 0, len));
OutputStream os = socket.getOutputStream();
// os.write("我是服务器".getBytes());
String servers = scanner.nextLine();
os.write(servers.getBytes());
// os.close();
// server.close();
}
}
}












posted @ 2020-04-16 15:26  葵儿啊  阅读(216)  评论(0编辑  收藏  举报
/*粒子线条,鼠标移动会以鼠标为中心吸附的特效*/