Java实现的基于socket通信的实例代码
程序员文章站
2023-12-11 21:49:40
服务器端代码:
复制代码 代码如下:import java.io.bufferedreader; import java.io.inputstreamreade...
服务器端代码:
复制代码 代码如下:
import java.io.bufferedreader;
import java.io.inputstreamreader;
import java.net.serversocket;
import java.net.socket;
public class server {
public static void main(string[] args) {
serversocket server;
try{
server = new serversocket(1111);
socket socket = server.accept();
bufferedreader br = new bufferedreader(new inputstreamreader(socket.getinputstream(),"utf-8"));
system.out.println(br.readline());
br.close();
socket.close();
server.close();
}catch (exception e) {
system.out.println(e);
}
}
}
客户端代码:
复制代码 代码如下:
import java.io.bufferedreader;
import java.io.inputstreamreader;
import java.io.printstream;
import java.net.socket;
public class client {
public static void main(string[] args) {
socket socket;
printstream ps;
try {
socket = new socket("127.0.0.1",1111);
system.out.println("connect successfully...");
system.out.println("please input some words to server:");
bufferedreader br = new bufferedreader(new inputstreamreader(system.in));
string content = null;
try {
content = br.readline();
} catch (exception e) {
}
ps = new printstream(socket.getoutputstream(),true,"utf-8");
ps.print(content);
socket.close();
} catch (exception e) {
system.out.println(e);
}
}
}