u012859234
warmqian
2016-03-19 13:27

TCPsocket实现一对一通信问题

  • java

只需要实现简单的通信,但是服务器没有提示,怎么改
import java.io.*;
import java.net.*;

class Client{
public static void main(String[] args) {
try {
Socket socket = new Socket("127.0.0.1", 5050);
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
out.writeUTF("我是客户机");//使用UTF-8编码传递字符串
DataInputStream in = new DataInputStream(socket.getInputStream());
String s = in.readUTF();
out.flush();
System.out.println("客户机收到:" + s);
in.close();
out.close();
socket.close();
}
catch (Exception e) {

    } 
    }
}

服务器端代码

import java.io.*;
import java.net.*;

class Server {
public static void main(String[] args) {
try {
ServerSocket s_socket = new ServerSocket(5050);
Socket socket = s_socket.accept();

        DataInputStream in = new DataInputStream(socket.getInputStream());
        DataOutputStream out = new DataOutputStream(socket.getOutputStream());
        boolean goon=true;
        String s;
        while (goon) {
        s = in.readUTF();

        if (!s.equals("byte")) {
        System.out.println("服务器收到:" + s);
        out.writeUTF("我是服务器");
        out.flush();
        }
        else {
        goon=false;
        out.writeUTF("byte");
        out.flush();     
        }
        in.close();
        out.close();    
        s_socket.close();
        }
        } catch (Exception e) {
        }   
    }
}

运行之后没显示

  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

1条回答