80,471
社区成员




public class TCPServer {
static int port = 9800;
public static void main(String[] args) throws IOException {
ServerSocket ss = new ServerSocket(port);
boolean again = true;
while (again) {
System.out.println("TCP服务器在" + port + "等待连接...");
Socket socket = ss.accept();
System.out.println("客户端IP: " + socket.getInetAddress() + "端口号" + socket.getPort() + "已连接进来!!!");
DataInputStream dInputStream = new DataInputStream(socket.getInputStream());
//读取用户发送的数据
String data = dInputStream.readUTF();
while(data != null){
System.out.println("客户端发送的数据是: " + data);
System.out.println("555");
}
dInputStream.close();
socket.close();
ss.close();
}
}
//用Socket为服务器传送数据
class NetThread extends Thread{
private TalkActivity talkActivity;
public NetThread(TalkActivity talkActivity) {
this.talkActivity = talkActivity;
}
@Override
public void run() {
try {
final Socket socket = new Socket("192.168.0.9", 9800);
os = socket.getOutputStream();
pw = new PrintWriter(os);
timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
try {
DataOutputStream dOutputStream = new DataOutputStream(socket.getOutputStream());
dOutputStream.writeUTF(data);
Log.i("peng", data);
dOutputStream.flush();
dOutputStream.close();
dOutputStream.flush();
dOutputStream.close();
} catch (Exception e) {
final String msg = e.getMessage();
//Toast.makeText(talkActivity, msg, Toast.LENGTH_SHORT).show();
}
}
}, 100, 10);
} catch (Exception e) {
final String msg = e.getMessage();
Toast.makeText(talkActivity, msg, Toast.LENGTH_SHORT).show();
}
}
}
while (again) {
System.out.println("TCP服务器在" + port + "等待连接...");
Socket socket = ss.accept();
System.out.println("客户端IP: " + socket.getInetAddress() + "端口号"
+ socket.getPort() + "已连接进来!!!");
DataInputStream dInputStream = new DataInputStream(
socket.getInputStream());
String data = "";
while (socket != null && socket.isConnected() && !socket.isClosed()
&& Thread.currentThread().isAlive()) {
while ((data = dInputStream.readUTF()) != null) {
System.out.println("客户端发送的数据是: " + data);
System.out.println("555");
}
}
//dInputStream.close();
// socket.close();
// ss.close();
}