*发送线程
import java.io.IOException; import java.io.OutputStream; import java.net.Socket; import java.util.Scanner; public class SendThread extends Thread { private Socket socket; public SendThread(Socket socket){ this.socket = socket; } @Override public void run() { //获得输出管道。 try { OutputStream os = socket.getOutputStream(); //接收键盘录入的数据。 Scanner input = new Scanner(System.in); String str = null; while(true){ str = input.nextLine(); os.write((str+"\r\n").getBytes()); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
*接收线程
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.Socket; public class ReceiverThread extends Thread { private Socket socket; public ReceiverThread(Socket socket){ this.socket = socket; } //接收数据。 @Override public void run() { //获得读取管道。 try { InputStream is = socket.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String ip = socket.getInetAddress().getHostAddress(); int port = socket.getPort(); String str = null; while(true){ if(socket==null){ break; } str = br.readLine(); System.out.println(ip+"-"+port+":"+str); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
*聊天客户端
import java.io.IOException; import java.net.Socket; import java.net.UnknownHostException; /* * 一个客户端与一个服务端进行聊天。 * 1:接收数据, * 2:发送数据。 * 同时进行。:线程。 一个线程负责接收数据,一个线程负责发送数据。 */ public class ChatClient { public static void main(String[] args) { try { Socket socket = new Socket("127.0.0.1",9988); //开启线程。 new SendThread(socket).start(); new ReceiverThread(socket).start(); } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
*聊天服务器端
import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; public class ChatServer { public static void main(String[] args) { try { ServerSocket ss = new ServerSocket(9988); Socket s = ss.accept(); new SendThread(s).start(); new ReceiverThread(s).start(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
时间: 2024-12-28 09:52:23