清醒时做事,糊涂时读书,大怒时睡觉,无聊时关注图老师为大家准备的精彩内容。下面为大家推荐Java实现的基于socket通信的实例代码,无聊中的都看过来。
【 tulaoshi.com - 编程语言 】
服务器端代码:
(本文来源于图老师网站,更多请访问http://www.tulaoshi.com/bianchengyuyan/)代码如下:
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);
}
}
}
来源:http://www.tulaoshi.com/n/20160219/1595921.html
看过《Java实现的基于socket通信的实例代码》的人还看了以下文章 更多>>