Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1698404
  • 博文数量: 210
  • 博客积分: 10013
  • 博客等级: 上将
  • 技术积分: 2322
  • 用 户 组: 普通用户
  • 注册时间: 2008-09-25 15:56
文章分类

全部博文(210)

文章存档

2011年(34)

2010年(121)

2009年(37)

2008年(18)

我的朋友

分类: Java

2009-05-16 19:40:25

客户端程序:

package socket;

 

import java.net.*;

import java.io.*;

 

public class Client{

Socket s=null;

DataInputStream inStream=null;

DataOutputStream outStream=null;

 

public Client() {

try{

init();

waitData();

}

catch(Exception e){

System.out.println(e.toString());

}

}

 

void init() throws Exception{

s=new Socket("219.223.242.144",9004); //把这里的IP改成你运行SocketServer.class的IP


inStream=new DataInputStream(s.getInputStream());

outStream=new DataOutputStream(s.getOutputStream());

s.setSoTimeout(3000);

}

 

void waitData(){

while(true){

try{

String str=inStream.readUTF();

System.out.println("Client accept: "+str);

str=Integer.toString(Integer.parseInt(str));

outStream.writeUTF(str);

}

catch(Exception e){

System.out.println(e.toString());

break;

}

}

}

 

public static void main(String[] args) {

    Client socketClient1 = new Client();

}

}

 

服务器端程序:

package socket;

 

import java.io.*;

import java.net.*;

 

public class socket {

ServerSocket ss=null;

Socket s=null;

DataInputStream inStream=null;

DataOutputStream outStream=null;

 

public socket() {

try{

init();

}

catch(Exception e){

System.out.println(e.toString());

}

}

 

void init() throws Exception{

ss=new ServerSocket(9004);

s.setSoTimeout(3000);

}

 

void waitForClient(){

try{

s=ss.accept();

inStream=new DataInputStream(s.getInputStream());

outStream=new DataOutputStream(s.getOutputStream());

outStream.writeUTF("1");

s.setSoTimeout(3000);

waitData();

}

catch(Exception e){

System.out.println(e.toString());

}

}

 

void waitData(){

while(true){

try{

String str=inStream.readUTF();

System.out.println("Server accept: "+str);

int nu=Integer.parseInt(str)+1;

if(nu>20){

System.out.println("Send end!");

break;

}

else{

str=Integer.toString(nu);

outStream.writeUTF(str);

}

}

catch(Exception e){

System.out.println(e.toString());

break;

}

}

}

 

public static void main(String[] args) {

    socket socketServer1 = new socket();

socketServer1.waitForClient();

}

}

阅读(8037) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~