package?client;
import?java.io.*;
import?java.net.*;
import?java.util.*;
import?java.awt.*;
import?javax.swing.*;
public?class?Server?{
@SuppressWarnings("resource")
public?static?void?main(String[]?args)?{
ServerSocket?server?=null;
ServerThread?thread;
Socket?you=?null;
while?(true)
{
try{server?=?new?ServerSocket(4331);}
catch?(IOException?e1){System.out.println("正在監(jiān)聽");}
try{you=server.accept();
System.out.println("客戶的地址:"+you.getInetAddress());}
catch(IOException?e){System.out.println("正在等待客戶");}
if(you!=null){
new?ServerThread(you).start();
}
}
}
}
class?ServerThread?extends?Thread
{
Socket?socket;
ObjectInputStream?in=null;
ObjectOutputStream?out?=null;
JFrame?window;
JTextArea?text;
ServerThread(Socket?t)
{
socket?=t;
try
{
out=new?ObjectOutputStream(socket.getOutputStream());
in?=new?ObjectInputStream(socket.getInputStream());
}
catch?(IOException?e){}
????????window?=new?JFrame();
????????text?=new?JTextArea();
????????for(int?i=1;i<=20;i++)
????????{
???????? text.append("你好,我是服務(wù)器上的文件區(qū)組件\n");
????????}
????????text.setBackground(Color.yellow);
????????window.add(text);
????????window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public?void?run(){
try{??out.writeObject(window);}
catch?(IOException?e){
System.out.println("客戶離開");
}
}
}
附客服代碼
package?client;
import?java.io.*;
import?java.net.*;
import?java.util.*;
public?class?Client?{
public?static?void?main(String?agrs[])
{
Scanner?scanner=?new?Scanner?(System.in);
Socket?mysocket=null;
ObjectInputStream?inObject=null;
ObjectOutputStream?outObject=null;
Thread?thread;
ReadWindow?readWindow?=null;
try?{
mysocket?=new?Socket();
readWindow?=new?ReadWindow();
thread?=new?Thread(readWindow);
System.out.println("輸入服務(wù)器的IP");
String?IP=scanner.nextLine();
System.out.println("輸入端口號:");
int?port?=scanner.nextInt();
if(mysocket.isConnected())
{
}
else?
{
InetAddress?address?=InetAddress.getByName(IP);
InetSocketAddress?socketAddress=new?InetSocketAddress(address,port);
mysocket.connect(socketAddress);
InputStream?in=mysocket.getInputStream();
????OutputStream?out=mysocket.getOutputStream();
????inObject=new?ObjectInputStream(in);
????outObject=new?ObjectOutputStream(out);
????readWindow.setObjectInputStream(inObject);
????thread.start();
}
}
catch(Exception?e)
{
System.out.println("服務(wù)器已經(jīng)斷開"+e);
}
}
}
class?ReadWindow?implements?Runnable
{
????ObjectInputStream?in;
????public?void?setObjectInputStream(?ObjectInputStream?in)
????{
???? this?.in=in;
????}
????public?void?run()
????{
???? double?result?=0;
???? while?(true)
???? {
???? try{
???? javax.swing.JFrame?window=(javax.swing.JFrame)in.readObject();
???? window.setTitle("這是從服務(wù)器上讀入的窗口");
???? window.setVisible(true);
???? window.requestFocusInWindow();
???? window.setSize(600,?800);
???? }
???? catch?(Exception?e)
???? {
???? System.out.println("服務(wù)器已經(jīng)斷開"+e);
???? break;
???? }
???? }
????}
}
添加回答
舉報
0/150
提交
取消