Java实现的基于socket通信的实例代码
程序员文章站
2022-04-25 17:44:00
...
服务器端代码:
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); } } }
更多Java实现的基于socket通信的实例代码相关文章请关注PHP中文网!
推荐阅读
-
Java实现简单的递归操作方法实例
-
php实例教程:使用php代码实现在网页上生成图片的步骤
-
CSS3实现的鼠标悬浮开门关门效果代码实例_html/css_WEB-ITnose
-
基于php socket(fsockopen)的应用实例分析_PHP教程
-
基于wxpython实现的windows GUI程序实例
-
jQuery实现可收缩展开的级联菜单实例代码_javascript技巧
-
memcache 用PHP写的基于Memcache的Queue实现代码
-
MySQL主从复制实战-详解基于日志点的复制代码实例
-
基于Python的移动联通基站接口调用代码实例
-
php编程实现获取excel文档内容的代码实例_php技巧