Java 的 Socket 服务器和客户端通信的例子 存在一个小问题
有木有好心的java coder 帮我解决下这个问题~~
这个程序写完了后 开两个命令窗口进行编译通信,竟然会不能正常通信,是不是因为我写的socket是一个线程的原因。但是为什么开两个eclipse ,每个下面运行一个服务器端,和用户端就可以。
import java.util.*; import java.io.*; import java.net.*; public class SS { //server public static void main(String args[]){ ServerSocket socketServer=null; DataInputStream in=null; DataOutputStream out=null; Socket server; try{ socketServer=new ServerSocket(2060); } catch(Exception e1){ System.out.println("can't estblish socketServer "+e1); } try{ Scanner cin=new Scanner(System.in); System.out.println("you are server ,please send message to client"); server=socketServer.accept(); in=new DataInputStream(server.getInputStream()); out=new DataOutputStream(server.getOutputStream()); while(true){ String send=null,receive=null; receive=in.readUTF(); System.out.println("get message from client is "+receive); System.out.println("send message from client"); send=cin.nextLine(); out.writeUTF(send); } } catch(Exception e){ System.out.println("break! "+e); } } }
import java.util.*; import java.io.*; import java.net.*; public class CC { //client public static void main(String args[]){ Socket client=null; DataInputStream in=null; DataOutputStream out=null; try{ client=new Socket("127.0.0.1",2060); in=new DataInputStream(client.getInputStream()); out=new DataOutputStream(client.getOutputStream()); System.out.println("You are a client,you send message to server"); Scanner cin=new Scanner(System.in); while(true){ String send=null,receive=null; System.out.println("Please input Client message sending to server!"); send=cin.nextLine(); out.writeUTF(send); receive=in.readUTF(); System.out.println("Message from Server is:"+receive); Thread.sleep(500); } } catch(Exception e){ System.out.println("break!"+e); } } }
我先运行的server,在运行的client~~ 在eclipse下就可以正常通信。