使用socket实现聊天功能
public class Service { //服务器 public static void main(String[] args) { ServerSocket serverSocket=null; Socket socket=null; //既然是 双方的通信 输入和输出流 必须有 OutputStream os=null; InputStream is=null; BufferedReader br=null; byte [] buf=new byte[1024]; int say; String word=null; try { serverSocket=new ServerSocket(8800); while(true){ //始终保持 畅通 socket=serverSocket.accept(); //实现多个窗口聊天 ThreadSocket socket2=new ThreadSocket(socket); socket2.start(); /*//打开所有的输入输出流 is=socket.getInputStream(); os=socket.getOutputStream(); //接收客户端的信息 say=is.read(buf); if (say!=0) { word =new String(buf, 0, say); } System.out.println(word); //给客户的回应 System.out.println("====请您输入需要回复的信息===="); br=new BufferedReader(new InputStreamReader(System.in)); os.write(br.readLine().getBytes()); //保证都是 最新的回复 */ } } catch (IOException e) { e.printStackTrace(); } finally{ try { br.close(); os.close(); is.close(); socket.close(); } catch (IOException e) { e.printStackTrace(); } } } }
public class ThreadSocket extends Thread { //相当于每一个单独的窗口 Socket socket = null; public ThreadSocket(Socket socket) { this.socket = socket; } @Override public void run() { String words = null; int say; InputStream is = null; OutputStream os = null; byte[] rece = new byte[1000]; try { //打开需要的 输入 输出流 is = socket.getInputStream(); os = socket.getOutputStream(); say = is.read(rece);// 接受客户端消息 if (say != 0) words = new String(rece, 0, say); System.out.println(words); BufferedReader bufferreader = new BufferedReader( new InputStreamReader(System.in)); os.write(("服务器====" + bufferreader.readLine()).getBytes());// 返回给客户端的响应 } catch (IOException e) { e.printStackTrace(); } finally { try { is.close(); os.close(); socket.close(); } catch (IOException e) { e.printStackTrace(); } } } }
public class Client { //客户端 public static void main(String[] args) { Socket socket=null; //既然是 双方的通信 输入和输出流 必须有 OutputStream os=null; InputStream is=null; InputStreamReader reader=null; byte [] buf=new byte[1024]; int say; String word=null; String server=null; String address=null; InetAddress host=null; try { System.out.println("亲爱的用户:请您输入服务器的ip地址:"); reader=new InputStreamReader(System.in); word=new BufferedReader(reader).readLine(); //获取用户的输入IP if (word!="") { address=word; // } //开始和服务器 交流 System.out.println("=======说出您想提问的问题======="); reader=new InputStreamReader(System.in); while(true){ word=new BufferedReader(reader).readLine();// 获取用户想说的话 server=word; //获取本机的IP host = InetAddress.getLocalHost(); word=host+"=====:"+server; //需要发送给 服务器的信息 socket=new Socket(InetAddress.getByName(address), 8800); //打开所有的输入输出流 is=socket.getInputStream(); os=socket.getOutputStream(); //设置通信的编码格式 os.write(word.getBytes("gbk")); //发送数据 //接收 say=is.read(buf); System.out.println("服务器说:"+new String(buf, 0, say)); } } catch (IOException e) { e.printStackTrace(); }finally{ try { os.close(); is.close(); socket.close(); reader.close(); } catch (IOException e) { e.printStackTrace(); } } } }