Java实现的基于socket通信的实例代码

时间:2021-05-20

服务器端代码:

复制代码 代码如下:
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);
}
}
}

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章