简单的java socket客户端和服务端示例
客户端
import java.io.bufferedreader;
import java.io.inputstreamreader;
import java.io.printwriter;
import java.net.socket;
public class myclient {
public static void main(string[] args) throws exception {
socket socket = new socket("localhost", 10000);
bufferedreader in = new bufferedreader(new inputstreamreader(socket.getinputstream()));
printwriter out = new printwriter(socket.getoutputstream());
bufferedreader reader = new bufferedreader(new inputstreamreader(system.in));
while (true) {
string msg = reader.readline();
out.println(msg);
out.flush();
if (msg.equals("bye")) {
break;
}
system.out.println(in.readline());
}
socket.close();
}
}
服务端
import java.io.bufferedreader;
import java.io.ioexception;
import java.io.inputstreamreader;
import java.io.printwriter;
import java.net.serversocket;
import java.net.socket;
public class myserver {
public static void main(string[] args) throws ioexception {
serversocket server = new serversocket(10000);
while (true) {
socket socket = server.accept();
invoke(socket);
}
}
private static void invoke(final socket client) throws ioexception {
new thread(new runnable() {
public void run() {
bufferedreader in = null;
printwriter out = null;
try {
in = new bufferedreader(new inputstreamreader(client.getinputstream()));
out = new printwriter(client.getoutputstream());
while (true) {
string msg = in.readline();
system.out.println(msg);
out.println("server received " + msg);
out.flush();
if (msg.equals("bye")) {
break;
}
}
} catch(ioexception ex) {
ex.printstacktrace();
} finally {
try {
in.close();
} catch (exception e) {}
try {
out.close();
} catch (exception e) {}
try {
client.close();
} catch (exception e) {}
}
}
}).start();
}
}
上一篇: 详解MySQL中的分组查询与连接查询语句
下一篇: Git将本地代码上传到码云