为什么服务器可以';在java中使用套接字时,是否无法从客户端读取布尔值?
我试着用2人在线制作卡罗游戏。我称之为“MrA”和“Mrb”。在我的程序中,当“Mra”邀请“Mrb”时,“Mrb”可以接受或拒绝。但当我试图在“Mrb”收到“Mra”的邀请后从“Mrb”向服务器发送数据时,出现了一个错误(“Mrb”可以从服务器读取数据,但不能回复服务器)。这是我的代码: 代码: 服务器: 输出: 服务器: Mra客户: Mrb客户: 更新:用户类: 注意:我首先保存了套接字。但它不起作用,我试着拯救河流为什么服务器可以';在java中使用套接字时,是否无法从客户端读取布尔值?,java,sockets,Java,Sockets,我试着用2人在线制作卡罗游戏。我称之为“MrA”和“Mrb”。在我的程序中,当“Mra”邀请“Mrb”时,“Mrb”可以接受或拒绝。但当我试图在“Mrb”收到“Mra”的邀请后从“Mrb”向服务器发送数据时,出现了一个错误(“Mrb”可以从服务器读取数据,但不能回复服务器)。这是我的代码: 代码: 服务器: 输出: 服务器: Mra客户: Mrb客户: 更新:用户类: 注意:我首先保存了套接字。但它不起作用,我试着拯救河流 package model; import java.io.DataI
package model;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class User {
private String userName;
private DataInputStream dataInputStream;
private DataOutputStream dataOutputStream;
private ObjectOutputStream objectOutputStream;
private ObjectInputStream objectInputStream;
public User() {
}
public User(String userName, DataInputStream dataInputStream, DataOutputStream dataOutputStream, ObjectOutputStream objectOutputStream, ObjectInputStream objectInputStream) {
this.userName = userName;
this.dataInputStream = dataInputStream;
this.dataOutputStream = dataOutputStream;
this.objectOutputStream = objectOutputStream;
this.objectInputStream = objectInputStream;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public DataInputStream getDataInputStream() {
return dataInputStream;
}
public void setDataInputStream(DataInputStream dataInputStream) {
this.dataInputStream = dataInputStream;
}
public DataOutputStream getDataOutputStream() {
return dataOutputStream;
}
public void setDataOutputStream(DataOutputStream dataOutputStream) {
this.dataOutputStream = dataOutputStream;
}
public ObjectOutputStream getObjectOutputStream() {
return objectOutputStream;
}
public void setObjectOutputStream(ObjectOutputStream objectOutputStream) {
this.objectOutputStream = objectOutputStream;
}
public ObjectInputStream getObjectInputStream() {
return objectInputStream;
}
public void setObjectInputStream(ObjectInputStream objectInputStream) {
this.objectInputStream = objectInputStream;
}
}
运行客户端
/*
*要更改此许可证标题,请在“项目属性”中选择“许可证标题”。
*要更改此模板文件,请选择工具|模板
*然后在编辑器中打开模板。
*/
包视图;
导入控制器。客户端;
导入javax.swing.JOptionPane;
/**
*
*@作者黄
*/
公共类LoginForm扩展了javax.swing.JFrame{
/**
*创建新表单LoginForm
*/
私人客户;
公共登录表单(){
初始化组件();
this.client=新客户端();
}
/**
*从构造函数中调用此方法来初始化表单。
*警告:不要修改此代码。此方法的内容始终为
*由表单编辑器重新生成。
*/
@抑制警告(“未选中”)
//
私有组件(){
jButton1=newjavax.swing.JButton();
jTextField1=newjavax.swing.JTextField();
jButton2=newjavax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jButton1.setText(“邀请”);
jButton1.addActionListener(新java.awt.event.ActionListener(){
public void actionPerformed(java.awt.event.ActionEvent evt){
jButton1ActionPerformed(evt);
}
});
jButton2.setText(“登录”);
jButton2.addActionListener(新java.awt.event.ActionListener(){
public void actionPerformed(java.awt.event.ActionEvent evt){
jButton2ActionPerformed(evt);
}
});
javax.swing.GroupLayout=newjavax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(布局);
layout.setHorizontalGroup(
createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(158158158)
.addComponent(jButton1)
.addContainerGap(javax.swing.GroupLayout.DEFAULT\u SIZE,Short.MAX\u VALUE))
.addGroup(layout.createSequentialGroup()
.addGap(84,84,84)
.addComponent(jTextField1,javax.swing.GroupLayout.PREFERRED_SIZE,111,javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED,72,Short.MAX_值)
.addComponent(jButton2)
.addGap(76,76,76))
);
layout.setVerticalGroup(
createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING,layout.createSequentialGroup()
.addGap(43,43,43)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextField1,javax.swing.GroupLayout.PREFERRED\u SIZE,javax.swing.GroupLayout.DEFAULT\u SIZE,javax.swing.GroupLayout.PREFERRED\u SIZE)
.addComponent(jButton2))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED,96,Short.MAX_值)
.addComponent(jButton1)
.addGap(115、115、115))
);
包装();
}//
私有void jButton2ActionPerformed(java.awt.event.ActionEvent evt){
//TODO在此处添加您的处理代码:
字符串userName=jTextField1.getText();
this.client.login(用户名);
System.out.println(“用户名:”+用户名);
}
私有void jButton1ActionPerformed(java.awt.event.ActionEvent evt){
//TODO在此处添加您的处理代码:
如果(本客户邀请(“Mra”)){
showMessageDialog(这是“邀请成功加入Mra”);
}
}
/**
*@param指定命令行参数
*/
公共静态void main(字符串参数[]){
/*设置Nimbus的外观和感觉*/
//
/*如果Nimbus(在JavaSE6中引入)不可用,请使用默认的外观。
*详情请参阅http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
试一试{
for(javax.swing.UIManager.LookAndFeelInfo:javax.swing.UIManager.getInstalledLookAndFeels()){
if(“Nimbus”.equals(info.getName())){
setLookAndFeel(info.getClassName());
打破
}
}
}捕获(ClassNotFoundException ex){
getLogger(LoginForm.class.getName()).log(java.util.logging.Level.SEVERE,null,ex);
}catch(实例化异常){
getLogger(LoginForm.class.getName()).log(java.util.logging.Level.SEVERE,null,ex);
}捕获(非法访问例外){
getLogger(LoginForm.class.getName()).log(java.util.logging.Level.SEVERE,null,ex);
}catch(javax.swing.UnsupportedLookAndFeelException ex){
getLogger(LoginForm.class.getName()).log(java.util.logging.Level.SEVERE,null,ex);
}
//
//
class ClientHandler implements Runnable {
private Socket socket;
private User userConnected;
private volatile boolean stop;
private ArrayList<User> listUsers;
private DataOutputStream dataOutStream;
private DataInputStream dataInStream;
private ObjectOutputStream objOutStream;
private ObjectInputStream objInStream;
public ClientHandler() {
}
public ClientHandler(Socket socket, ArrayList<User> listUsers) {
this.socket = socket;
this.listUsers = listUsers;
this.userConnected = null;
this.stop = false;
try {
dataOutStream = new DataOutputStream(socket.getOutputStream());
dataInStream = new DataInputStream(socket.getInputStream());
objOutStream = new ObjectOutputStream(socket.getOutputStream());
objInStream = new ObjectInputStream(socket.getInputStream());
} catch (IOException e) {
System.out.println("Error when create in/output stream! " + e);
}
}
@Override
public void run() {
while (!stop) {
try {
String code = dataInStream.readUTF();
switch (code) {
case "login": {
loginUser();
}
break;
case "invite": {
boolean inviteSucess = inviteUser();
dataOutStream.writeBoolean(inviteSucess);
dataOutStream.flush();
}
break;
}
// display user login success
for (User user : listUsers) {
System.out.println("User Name:" + user.getUserName());
}
System.out.println("+++++++++++++");
} catch (IOException e) {
try {
socket.close();
dataInStream.close();
dataOutStream.close();
objInStream.close();
objOutStream.close();
} catch (IOException ex) {
System.out.println("Can not close connection! " + ex);
}
stop = true;
}
}
}
private void loginUser() {
try {
String userName = dataInStream.readUTF();
userConnected = new User(userName, dataInStream, dataOutStream, objOutStream, objInStream);
listUsers.add(userConnected);
} catch (IOException e) {
System.out.println(e);
}
}
private boolean inviteUser() {
boolean inviteSucces = false;
try {
String invitedName = dataInStream.readUTF();
for (User user : listUsers) {
if (user.getUserName().equals(invitedName)) {
user.getDataOutputStream().writeUTF("invite");
user.getDataOutputStream().flush();
user.getDataOutputStream().writeUTF(userConnected.getUserName());
user.getDataOutputStream().flush();
System.out.println("send username success");
inviteSucces = user.getDataInputStream().readBoolean(); //error here. user.getDataInputStream() can not read boolean from client.
System.out.println(inviteSucces+ "read boolean from client success");
}
}
} catch (IOException e) {
System.out.println(e);
}
return inviteSucces;
}
}
package controller;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
public class Client implements Runnable {
private Socket socket;
private final int PORT = 4444;
private final String HOST = "localhost";
private volatile boolean stop;
private DataOutputStream dataOutStream;
private DataInputStream dataInStream;
private ObjectOutputStream objOutStream;
private ObjectInputStream objInStream;
public Client() {
try {
this.socket = new Socket(HOST, PORT);
this.stop = false;
try {
dataOutStream = new DataOutputStream(socket.getOutputStream());
dataInStream = new DataInputStream(socket.getInputStream());
objOutStream = new ObjectOutputStream(socket.getOutputStream());
objInStream = new ObjectInputStream(socket.getInputStream());
Thread t = new Thread(this);
t.start();
} catch (IOException e) {
System.out.println("Error when create in/output stream! " + e);
}
} catch (IOException e) {
System.out.println("Can not create client server! " + e);
}
}
@Override
public void run() {
while (!stop) {
try {
String code = dataInStream.readUTF();
switch (code) {
case "invite": {
String userInvite = dataInStream.readUTF();
System.out.println("Inviter name:"+userInvite);
System.out.println("Before send true to server");
dataOutStream.writeBoolean(true);
System.out.println("After send true to server");
dataOutStream.flush();
}
break;
}
} catch (IOException e) {
System.out.println("Can not read from dataInStream! " + e);
try {
socket.close();
dataInStream.close();
dataOutStream.close();
objInStream.close();
objOutStream.close();
} catch (IOException ex) {
System.out.println("Can not close connection! " + ex);
}
stop = true;
}
}
}
public void login(String userName) {
try {
dataOutStream.writeUTF("login");
dataOutStream.flush();
dataOutStream.writeUTF(userName);
dataOutStream.flush();
} catch (IOException e) {
System.out.println(e);
}
}
public boolean invite(String invitedName){
boolean inviteSucess = false;
try {
dataOutStream.writeUTF("invite");
dataOutStream.flush();
dataOutStream.writeUTF(invitedName);
dataOutStream.flush();
inviteSucess = dataInStream.readBoolean();
} catch (IOException e) {
System.out.println(e);
}
return inviteSucess;
}
}
Server start at port 4444
Connect to server success!
Connect to server success!
User Name:Mra
+++++++++++++
User Name:Mra
User Name:Mrb
+++++++++++++
send username success
User Name: Mra
Inviter name:Mrb
Before send true to server
After send true to server
User Name: Mrb
package model;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class User {
private String userName;
private DataInputStream dataInputStream;
private DataOutputStream dataOutputStream;
private ObjectOutputStream objectOutputStream;
private ObjectInputStream objectInputStream;
public User() {
}
public User(String userName, DataInputStream dataInputStream, DataOutputStream dataOutputStream, ObjectOutputStream objectOutputStream, ObjectInputStream objectInputStream) {
this.userName = userName;
this.dataInputStream = dataInputStream;
this.dataOutputStream = dataOutputStream;
this.objectOutputStream = objectOutputStream;
this.objectInputStream = objectInputStream;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public DataInputStream getDataInputStream() {
return dataInputStream;
}
public void setDataInputStream(DataInputStream dataInputStream) {
this.dataInputStream = dataInputStream;
}
public DataOutputStream getDataOutputStream() {
return dataOutputStream;
}
public void setDataOutputStream(DataOutputStream dataOutputStream) {
this.dataOutputStream = dataOutputStream;
}
public ObjectOutputStream getObjectOutputStream() {
return objectOutputStream;
}
public void setObjectOutputStream(ObjectOutputStream objectOutputStream) {
this.objectOutputStream = objectOutputStream;
}
public ObjectInputStream getObjectInputStream() {
return objectInputStream;
}
public void setObjectInputStream(ObjectInputStream objectInputStream) {
this.objectInputStream = objectInputStream;
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package view;
import controller.Client;
import javax.swing.JOptionPane;
/**
*
* @author hoang
*/
public class LoginForm extends javax.swing.JFrame {
/**
* Creates new form LoginForm
*/
private Client client;
public LoginForm() {
initComponents();
this.client = new Client();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jButton1 = new javax.swing.JButton();
jTextField1 = new javax.swing.JTextField();
jButton2 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jButton1.setText("Invite");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButton2.setText("Login");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(158, 158, 158)
.addComponent(jButton1)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGap(84, 84, 84)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 111, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 72, Short.MAX_VALUE)
.addComponent(jButton2)
.addGap(76, 76, 76))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(43, 43, 43)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton2))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 96, Short.MAX_VALUE)
.addComponent(jButton1)
.addGap(115, 115, 115))
);
pack();
}// </editor-fold>
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String userName = jTextField1.getText();
this.client.login(userName);
System.out.println("User Name: "+userName);
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
if(this.client.invite("Mra")){
JOptionPane.showMessageDialog(this, "Invite success to Mra");
}
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(LoginForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(LoginForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(LoginForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(LoginForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new LoginForm().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JTextField jTextField1;
// End of variables declaration
}