日期:2014-05-19  浏览次数:20706 次

java scoket问题
服务器端往客户端发数据没反应


package com.angogps.socket;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.ParseException;
import java.util.Map;

public class MeiTrackSocketServer extends Thread {
private Socket client;

public MeiTrackSocketServer(Socket c) {
this.client = c;
}

public void run() {
try {
HttpRequester requester=new HttpRequester();


BufferedReader in = new BufferedReader(new InputStreamReader(
client.getInputStream()));

OutputStreamWriter out = new OutputStreamWriter (client.getOutputStream());

 
String str = in.readLine();
while((str=in.readLine())!=null){
SocketResolve sResolve=new SocketResolve();
System.out.println(str);

String address=client.getInetAddress().getHostAddress().toString();

System.out.println(address);

System.out.println(client.getPort());
Map<String, String> map =sResolve.toMap(str);
map.put("cip", address);
map.put("pr",((Integer)client.getPort()).toString());

}


out.write("@@S28,012896000469921,A11,10*FD\r\n");
out.flush();












client.close();
} catch (IOException ex) {
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {

}
}

public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket(5678);
while (true) {
MeiTrackSocketServer mts = new MeiTrackSocketServer(server.accept());

mts.start();

}
}
}

------解决方案--------------------
lz你没有理解Socket的运行原理。
socket通信首先需要一个ServerSocket开启一个监听端口,然后通过socket的accept()方法等待客户端连接。
当有客户端连接(通过服务器的IP和监听端口号)时,accept方法会返回一个Socket对象,这样客户端和服务器端就建立好连接了(如果想建立多个连接可以将accept方法放到循环里,将返回的Socket对象保存下来),然后通过该Socket建立输入输出流通道,通过输入输出发送和接收消息。服务器端通过获取的Socket对象可以获得客户端的IP,主机名、输入输出流、等等信息,通过连接对象建立的IO流直接可以发送和接收消息了。