TCP网络编程一对一聊天
需求:使用TCP协议实现两台电脑间的交互聊天
import java.io.IOException;
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(8080);
Socket socket = server.accept();
Scanner scan = new Scanner(System.in);
new ReceiveThread(socket).start();
PrintStream ps = new PrintStream(socket.getOutputStream());
String str="";
while (true){
str = scan.next();
ps.println("服务器:"+str);
}
}
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
public class ReceiveThread extends Thread{
private Socket socket;
public ReceiveThread(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
BufferedReader br=null;
try {
br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
String s =null;
while(true){
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(s);
}
}
}
import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;
import java.util.Scanner;
public class Client {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("127.0.0.1", 8080);
Scanner scan = new Scanner(System.in);
new ReceiveThread(socket).start();
PrintStream ps = new PrintStream(socket.getOutputStream());
String str="";
while(true){
str = scan.next();
ps.println("客户端: "+str);
}
}
}
注:此次代码未实现3次招手,4次挥手。而且客户端与服务器的一对一聊天也并不适用于各种聊天软件,本代码仅是一个为了认识TCP交互而做的Demo。 运行顺序:先运行服务器再运行客户端,否则报错
|