你的服务器端无限循环接受信息那段有问题,你只能readline到一次,我把你的代码稍微改了下,测试能进行聊天:
服务端:
import java.net.*; import java.io.*; public class TCPServer { public static void main(String[] args) { try { ServerSocket ss = new ServerSocket(5550); Socket s = null; while (true) { s = ss.accept(); BufferedReader br = new BufferedReader(new InputStreamReader(s .getInputStream())); System.out.println("一个客户端已连接上来"); String msg = ""; PrintWriter pw = new PrintWriter(s.getOutputStream()); while ((msg=br.readLine())!=null) { System.out.println("22222"); System.out.println("客户端说:" + msg); pw.println("我是服务器,你刚才说了:" + msg); pw.flush(); if (msg.equals("bye")) { break; } } pw.close(); ss.close(); } } catch (Exception e) { e.printStackTrace(); } } }
客户端:
import java.io.*; import java.net.*; public class TCPClient { public static void main(String[] args) { try { Socket s = new Socket("127.0.0.1", 5550); BufferedReader bw = new BufferedReader(new InputStreamReader( System.in)); BufferedReader br = new BufferedReader(new InputStreamReader(s .getInputStream())); PrintWriter pw = new PrintWriter(s.getOutputStream()); String st = bw.readLine(); while (!st.equals("bye")) { pw.println(st); pw.flush(); System.out.println("服务器端说:" + br.readLine()); st = bw.readLine(); } br.close(); bw.close(); bw.close(); s.close(); } catch (Exception e) { e.printStackTrace(); } finally { } } }
还有socket变成楼主可以用mina做服务端哦~非常好用的东东~呵呵~
把服务器端的防火墙关了
你先在本机上试一下来确认是不是IP地址的问题,程序粗略的看了下没什么问题
server打开没!
程序没错的,