java

位置:IT落伍者 >> java >> 浏览文章

利用Socket进行Java网络编程(三)


发布日期:2018年03月01日
 
利用Socket进行Java网络编程(三)

作者 郗旻

服务器的实现代码

import *;

import javaio*;

import javaawteventActionEvent;

import javaawteventActionListener;

public class talkServer

{ public static void main(String[] args)

{ try

{ file://建立服务器

ServerSocket server = new ServerSocket();

int i=;

for(;;)

{ Socket incoming = serveraccept()

new ServerThread(incomingi)start();

i++;

}

}catch (IOException ex){

exprintStackTrace();

}

}

}

class ServerThread extends Thread implements ActionListener

{

private int threadNum;

private Socket socket;

talkServerFrm t;

BufferedReader in;

PrintWriter out;

private boolean talking=true;

public ServerThread(Socket sint c)

{ threadNum = c;

socket = s;

}

public void actionPerformed(ActionEvent e)

{ Object source = egetSource();

try{

if(source==tbtnSend)

{ outprintln(tgetTalk());

tclearTalk();

}else

if(source==tbtnEnd)

{ outprintln(谈话过程被对方终止);

outclose();

inclose();

talking = false;

}

}catch(IOException ex){

}

}

public void run()

{ try{

t=new talkServerFrm(new Integer(threadNum)toString()this);

tsetSize();

tshow();

in = new BufferedReader(new

InputStreamReader(socketgetInputStream()));

out = new PrintWriter(socketgetOutputStream()true);

}catch(Exception e){

}

new Thread()

{ public void run()

{ try{

while(true)

{ checkInput();

sleep();

}

}catch (InterruptedException ex){

}catch(IOException ex){

}

}

}start();

while(talking)

{ }

tdispose();

}

private void checkInput() throws IOException

{ String line;

if((line=inreadLine())!=null)

tsetPartner(line); file://这是界面类里的方法

file://用来将line的内容输出到用户界面

}

}

               

上一篇:Java获取窗口鼠标坐标以及键盘按键

下一篇:用JNI实现一个高精度的Java计时器