首页 > 学院 > 开发设计 > 正文

socket通信程序------传达文字

2019-11-06 06:37:27
字体:
来源:转载
供稿:网友
package L15.L;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.net.ServerSocket;import java.net.Socket;/** * Created by fangjiejie on 2017/3/6. * 服务端:接收端 */public class M { public static void main(String[] args) throws IOException { ServerSocket server = new ServerSocket(9800);/*创建一个ServerSocket类,同时在运行该语句的计算机 的指定端口处建立一个监听服务*/ Socket client=server.accept();/*该语句调用了ServerSocket对象的accept()方法, 这个方法的执行将使Server端的程序处于等待状态,程序将一直阻塞直到捕捉到一个来自Client端的请求, 并返回一个用于与该Client通信的Socket对象client。此后Server程序只要向这个Socket对象读写 数据,就可以实现向远端的Client读写数据。结束监听时,关闭ServerSocket对象:*/ InputStream is=client.getInputStream();//用输入字节流读取, BufferedReader br=new BufferedReader(new InputStreamReader(is));//字节流转化为字符输入流 boolean flag=true; while(flag){ String Word=br.readLine();//将字符读取到word中 if(word.trim().toLowerCase().equals("q")){ System.out.PRintln("byebye"); flag=false; } else { System.out.println(word); } } }}package L15.L;import java.io.IOException;import java.io.PrintWriter;import java.net.Socket;import java.util.Scanner;/** * Created by fangjiejie on 2017/3/6. * 客户端:发送端 *///PrintWriter out=new PrintWriter(cilent.getOutputString(),true); true 自动Flashpublic class N { public static void main(String[] args) { try { Socket client=new Socket("127.0.0.1",9800);/*Socket类的构造函数有两个参数, 第一个参数是欲连接到的Server计算机的主机地址,第二个参数是该Server机上提供服务的端口号。*/ PrintWriter out=new PrintWriter(client.getOutputStream(),true); /*client.getOutputStream()就是返回一个服务器与客户端的输出流,true是对PrintWriter out而言,就是强行把缓冲区的数据输出。client.getOutputStream()返回的是一个节点流,在 它上面又套上了一个处理流PrintWriter ,便于输出数据。*/ Scanner sc=new Scanner(System.in); while (sc.hasNext()){ String word=sc.nextLine(); out.println(word); } out.close(); sc.close(); client.close(); } catch (IOException e) { e.printStackTrace(); } }}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表