欢迎来到天天文库
浏览记录
ID:40557499
大小:15.86 KB
页数:9页
时间:2019-08-04
《javasocket通信》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、1:Servlet端importjava.awt.*;importjava.awt.event.*;importjavax.swing.*;importjava.io.*;importjava.net.*;publicclassMultiClientServer{publicstaticvoidmain(String[]args){newServer();}}classServer{staticintport=0;staticintstartStatus=0;Server(){try{ServerFrameserverFrame=newServerFrame("Mu
2、ltiClientSever");while((startStatus==0)
3、
4、(port==0)){Thread.currentThread().sleep(120);}ServerSocketserverSocket=newServerSocket(port,6);intclientSort=0;for(inti=0;;i++){Socketsocket=serverSocket.accept();clientSort++;PrintWriterout=newPrintWriter(socket.getOutputStream());BufferedReade
5、rin=newBufferedReader(newInputStreamReader(socket.getInputStream()));Threadth=newThread(newCommunicate(socket,clientSort,out,in));th.start();}}catch(Exceptionm){System.out.println("ERROR"+m);}}}//线程运行类classCommunicateimplementsRunnable{intclientSort;Socketsocket;PrintWriterout;Buffered
6、Readerin;JTextAreaarea3;Communicate(Socketsocket,intclientSort,PrintWriterout,BufferedReaderin){this.socket=socket;this.clientSort=clientSort;this.out=out;this.in=in;}publicvoidrun(){try{area3=newJTextArea();ClientWithServerclientWithServer=newClientWithServer(clientSort,out,area3);out
7、.println("已成功连接至服务器.");out.flush();StringacceptString;while(!(acceptString=in.readLine()).equals("bye")){area3.append("Client:"+acceptString+"");}in.close();out.close();socket.close();}catch(Exceptiong){System.out.println("Error:"+g);}}}//服务器与客户端通信窗口classClientWithServer{JFrameframe3
8、;JTextAreaarea3;JTextFieldfield3;JButtonbutton3;intx=200;inty=150;intwidth=400;intheight=500;PrintWriterout;ClientWithServer(intclientRank,PrintWriterout,JTextAreaar){this.out=out;area3=ar;System.out.println("4");frame3=newJFrame("CommunicatewithClient"+clientRank);frame3.setLayout(n
9、ull);frame3.setLocation(x,y);frame3.setSize(width,height);JPanelpanel3=newJPanel();JScrollPanescrollPane3=newJScrollPane(area3);frame3.add(scrollPane3);frame3.add(panel3);scrollPane3.setLocation(0,0);scrollPane3.setSize(width,(height*4/5));scrollPane3.setBackground(Color.WHITE);panel
此文档下载收益归作者所有