这是服务端代码
[code="java"]
package com.hj.demo.socket;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public Server() throws IOException {
ServerSocket ss = new ServerSocket(7777);
while (true) {
Socket sk = ss.accept();
ClientThread ct = new ClientThread(sk);
ct.start();
System.out.println("服务端已启动...");
}
}
// 多线程客户端
class ClientThread extends Thread {
private Socket clientSocket = null;
public ClientThread(Socket clientSocket) {
this.clientSocket = clientSocket;
}
DataInputStream dis = new DataInputStream(null);
@SuppressWarnings("deprecation")
@Override
public void run() {
// TODO Auto-generated method stub
String hostName = clientSocket.getInetAddress().toString();
System.out.println("hostName:>" + hostName+"已连接");
String msg = null;
try {
dis = new DataInputStream(clientSocket
.getInputStream());
while (true) {
msg = dis.readUTF();
System.out.println(hostName + "发来的消息>: " + msg);
if(null==dis.readLine()||"".equals(dis.readLine())){
break;
}
}
if(!"".equals(msg)&&msg.length()!=0){
DataOutputStream dos = new DataOutputStream(clientSocket.getOutputStream());
String rep = "我是返回给由"+hostName+"发来["+msg+"]的消息";
System.out.println(rep);
dos.writeUTF(rep);
dos.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
super.run();
}
}
public static void main(String[] args) throws IOException {
new Server();
}
}
[/code]
这是客户端的代码
[code="java"]
package com.hj.demo.socket;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client {
public static void main(String[] args) throws UnknownHostException,
IOException, InterruptedException {
Socket sk = new Socket("127.0.0.1", 7777);
DataOutputStream dos = new DataOutputStream(sk.getOutputStream());
DataInputStream dis = new DataInputStream(sk.getInputStream());
dos.writeUTF("hello,world");
String rep = dis.readUTF();
System.out.println("主机返回的消息>: " + rep);
dos.close();
dis.close();
}
}
[/code]
服务端可以接收发来的消息,但是返回就不行,求解答!