服务器 客户端 连续 发送实现2--socket
首先感谢我宿友廖某的指导
服务器
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket(5050);
while (true) {
Socket client = server.accept();
System.out.println(client.getPort() + "已上线");
clientserver c = new clientserver(client);
Scanner sc = new Scanner (System.in);
String str = sc.nextLine();
c.setName(str);
c.start();
}
}
}
class clientserver extends Thread {
Socket client;
clientserver(Socket socket) {
this.client = socket;
}
public void run() {
System.out.println("与" + client.getInetAddress() + "连接成功");
try {
BufferedReader input = new BufferedReader(new InputStreamReader(client.getInputStream()));
PrintStream print = new PrintStream(client.getOutputStream());
boolean flag = true;
while (flag) {
String s = input.readLine();
if (s.equals("bye")) {
flag = false;
System.out.println(client.getInetAddress()+"退出连接");
} else {
System.out.println(s);
}
}
} catch (Exception e) {
System.out.println("连接异常" + client.getPort() + "已下线");
}
}
}
客户端
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.util.Scanner;
public class Client extends Thread {//把客户端弄成线程的话 就可以实现客户端持续给服务器发信息 不用对方收到
Socket client;
Client(Socket client) {
this.client = client;
}
while (true) {
try {
PrintStream print = new PrintStream(client.getOutputStream());
Scanner scanner = new Scanner(System.in);
String send = scanner.nextLine();
print.println(send);
} catch (Exception e) {
System.out.println(e);
}
}
}
public static void main(String[] args) {
try {
Socket socket = new Socket("localhost", 5050);
Client c = new Client(socket);
c.start();
System.out.println("与" + socket.getInetAddress() + "连接成功");
try {
BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while (true) {
String str = input.readLine();
System.out.println(str);
}
} finally {
socket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
https://blog.csdn.net/o0DarkNessYY0o/article/details/52410980