Chinaunix首页 | 论坛 | 博客
  • 博客访问: 22159
  • 博文数量: 22
  • 博客积分: 960
  • 博客等级: 准尉
  • 技术积分: 260
  • 用 户 组: 普通用户
  • 注册时间: 2009-10-06 12:49
文章分类
文章存档

2011年(1)

2009年(21)

我的朋友
最近访客

分类: Java

2009-10-06 12:55:01

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();

}

}

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