在我的Java程序中,我创建了两个套接字,其中一个是serversocket,其中一个就是普通套接字。
我在端口1234设置了serverSocket,并使另一个普通端口监听localhost:1234。
虽然套接字没有收到我发送给它的任何消息。
附:它还在我的另一个Java程序上接收在同一端口上侦听的消息。但不是来自同一个程序,同时包含serversocket和普通套接字。
左编辑:这是我的代码。
public void initLan(){
try{
if(mode == GameMode.TWO_PLAYER_LAN_HOST){
serverSocket = new ServerSocket(port);
System.out.println("Waiting for client to connect....");
socket = serverSocket.accept();
serverInputSocket = new Socket("localhost",port);
lanHostInput = new BufferedReader(new InputStreamReader(serverInputSocket.getInputStream()));
lanHostOutput = new PrintWriter(serverInputSocket.getOutputStream(),true);
}else if(mode == GameMode.TWO_PLAYER_LAN_CLIENT){
socket = new Socket("localhost",port);
}
lanOutput = new PrintWriter(socket.getOutputStream(),true);
lanInput = new BufferedReader(new InputStreamReader(socket.getInputStream()));
}catch(Exception e){
System.out.println("Could not initialize LAN");
}
}
这是我按下向上键时发送的信息
if(keyCode == KeyEvent.VK_UP){
lanOutput.print("UP\n");
lanOutput.flush();
lanHostOutput.print("UP\n");
lanHostOutput.flush();
//System.out.println("UP");
}
当我发送信息时,以后就不再收到该信息。
if(lanInput.ready()){
String message = lanInput.readLine();
System.out.println(message);
if(message.contains("UP")){
snake.move("UP");
System.out.println("moved up");
}
}
if(mode == GameMode.TWO_PLAYER_LAN_HOST){
if(lanHostInput.ready()){
String message = lanInput.readLine();
System.out.println(message);
if(message.contains("UP")){
snake.move("UP");
System.out.println("moved up");
}
}
}
答案 0 :(得分:1)
java中有两个类用于socket 1)java.net.Socket:用于客户端套接字 2)java.net.ServerSocket:用于服务器套接字
您只能侦听服务器套接字而不是客户端套接字
问题是这两行
using (var ctx = new DBContext())
{
InteractiveViews
.SetViewCacheFactory(
ctx,
new FileViewCacheFactory(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"\views.xml"));
}
用这个替换它们
socket = serverSocket.accept();
serverInputSocket = new Socket("localhost",port);