感谢大家看到我的问题。 我想用java解释我在Socket上的问题。 使用套接字,一个用于服务器等待来自客户端的连接,另一个用于客户端与服务器连接。 有两个问题~~使用java编码运行服务器和客户端应用程序
(1)
+++之后它们都彼此连接,所述两个侧可以交换消息给对方。我已经用服务器和客户端完成了两个应用程序代码,每个代码都有自己的主要代码THREAD,但我不能让它们彼此通信。我使用Windows命令来运行这两个文件.class。我先运行服务器,然后运行客户端。他们不能相互沟通。我想知道这是否是一个堵塞问题。如果我建立另一个线程,这个问题可以解决? (2)我试图在两个eclipse上运行这两个应用程序,换句话说每个eclipse运行一个应用程序。为什么这个问题可以解决?
(3)这里是我的代码客户端:
import java.util.*;
import java.io.*;
import java.net.*;
public class CC {
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);
}
}
}
这里是我的服务器
import java.util.*;
import java.io.*;
import java.net.*;
public class SS {
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);
}
}
}
“他们都互相联系后,双方可以互相交换信息”,“但我不能让他们相互沟通”是冲突的。你在每个这些程序的控制台上看到什么?另外,除非要将输入从服务器发送到客户端,否则在服务器代码中不需要“扫描程序”。 – asgs 2013-04-04 17:43:55