问题描述
- TCPsocket实现一对一通信问题
- 只需要实现简单的通信,但是服务器没有提示,怎么改
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) { } }}
运行之后没显示
解决方案
我测试了,服务器可以收到数据呀,没问题的