好的,所以就像标题所说的那样,我很难知道如何通过输入和输出流发送字符串。我正在制作一个基本的登录服务器,并希望能够点击"登录"并具有登录凭据以保存在服务器端。这就是我所拥有的。
这是我登录按钮的动作事件中的try块:
try {
Socket socket = Client.s;
OutputStream dOut = Client.s.getOutputStream();
PrintWriter socketOut = new PrintWriter(dOut);
username = jTextField1.getText();
password = jPasswordField1.getText();
//System.out.println("Username: " + username);
//System.out.println("Password: " + password);
socketOut.println(username);
socketOut.flush();
socketOut.println(password);
socketOut.flush();
socketOut.println("Click");
socketOut.flush();
} catch (Exception e){
e.printStackTrace();
}
这是我的代码服务器支持的代码。我试图接收和存储数据,但它不起作用,我不太清楚为什么。我还有一些无用的循环,我最终将删除(忽略这些):
BufferedReader socketIn = new BufferedReader(new InputStreamReader(s.getInputStream()));
String str = socketIn.readLine();
while (buttonClicked == false){
int done = 0;
String messageType = socketIn.toString();
while(done == 0) {
switch(messageType)
{
case "username": // Type A
username = socketIn.toString();
System.out.println("username: " + username);
break;
case "password": // Type B
password = socketIn.toString();
System.out.println("Password: " + password);
break;
case "Click":
buttonClicked = true;
break;
}
请注意,我知道我错过了右括号,我只复制了部分代码。
答案 0 :(得分:1)
BufferedReader socketIn = new BufferedReader(new InputStreamReader(s.getInputStream()));
String str = socketIn.readLine();
while (buttonClicked == false){
int done = 0;
String messageType = socketIn.toString();
while(done == 0) {
switch(messageType)
{
case "username": // Type A
username = socketIn.toString();
System.out.println("username: " + username);
break;
case "password": // Type B
password = socketIn.toString();
System.out.println("Password: " + password);
break;
case "Click":
buttonClicked = true;
break;
}
您获取了流.toString()
的{{1}},您应该使用socketIn.toString();
。
str
但是,无论如何我认为这不是你想要的......我的意思是当他通过"密码"时,密码将是密码。
也许你想要
BufferedReader socketIn = new BufferedReader(new InputStreamReader(s.getInputStream()));
String str = socketIn.readLine();
while (buttonClicked == false){
int done = 0;
while(done == 0) {
switch(str)
{
case "username": // Type A
username = str;
System.out.println("username: " + username);
break;
case "password": // Type B
password = str;
System.out.println("Password: " + password);
break;
case "Click":
buttonClicked = true;
break;
}
从输入中读取新行。