日期:2014-05-17 浏览次数:20831 次
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;
import java.util.List;
public class TCPPCServer {
static ServerSocket ss;
static InputStream in = null;
static OutputStream out = null;
static String sendMsgA = "";
static String sendMsgB = "";
static int portA = 0;
static int portB = 0;
static SocketAddress addressA = null;
static SocketAddress addressB = null;
static List<Socket> list = null;
public static void main(String[] args) {
try {
ss = new ServerSocket(3234);
System.out.println("成功建立客户端!");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while (!ss.isClosed()) {
try {
Socket socket = ss.accept();
// list.add(socket);
System.out.println("有一个客户端连接来了!====本地IP:"+socket.getLocalAddress()+"\nNAT端口:"+socket.getPort()+"\nNATIP:"+socket.getInetAddress());
// in = socket.getInputStream();
// out = socket.getOutputStream();
// String message = receive();
//
// if (message.contains("A")) {
// portA = socket.getPort();
// addressA = socket.getLocalSocketAddress();
// sendMsgA = "host:" + addressA + "|" + portA;
// System.out.println(sendMsgA);
//
// }
// if (message.contains("B")) {
// portB = socket.getPort();
// addressB = socket.getLocalSocketAddress();
// sendMsgB = "host:" + addressB + "|" + portB;
// System.out.println(sendMsgB);
//
// }
// // 两个都接收到后分别A、B地址交换互发
// if (!sendMsgA.equals("") && !sendMsgB.equals("")) {
// sendMsg(addressA, portA, sendMsgA, list.get(1));
// sendMsg(addressB, portB, sendMsgB, list.get(0));
// sendMsgA = "";
// sendMsgB = "";
// }
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private static String receive() {
String remsg = "";
try {
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int len = 0;
len = in.read();
while (true) {
if ((len = in.read(buffer, 0, len)) > 0) {
remsg = new String(buffer);
}
}
} catch (IOException e) {
// TODO Auto-generated catch&