Java开发网 Java开发网
注册 | 登录 | 帮助 | 搜索 | 排行榜 | 发帖统计  

您没有登录

» Java开发网 » Java SE 综合讨论区  

按打印兼容模式打印这个话题 打印话题    把这个话题寄给朋友 寄给朋友    该主题的所有更新都将Email到你的邮箱 订阅主题
flat modethreaded modego to previous topicgo to next topicgo to back
作者 请教:多线程Socket输出的意外
rjyang





发贴: 9
积分: 0
于 2005-03-08 16:38 user profilesend a private message to usersearch all posts byselect and copy to clipboard. 
ie only, sorry for netscape users:-)add this post to my favorite list
服务器程序:
import java.io.*;
import java.net.*;
public class Server3 extends Thread
{
Socket socket1;
public Server3(Socket s)
{
socket1=s;
start();//Calls run()
}
public void run()
{
try
{
BufferedReader in=new BufferedReader(new InputStreamReader(socket1.getInputStream()));
PrintWriter out=new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket1.getOutputStream())));
for(int i=0;i<5;i++)
{
String str=in.readLine();
System.out.println("Server receives"+str);
out.println("Server return back"+str);
}
System.out.println("closing...");
}
catch(IOException e)
{
System.err.println("IOException");
}
finally
{
try
{
socket1.close();
}
catch(IOException e)
{
System.err.println("Socket not closed");
}
}
}
static final int PORT=8000;
public static void main(String[] args) throws IOException
{
ServerSocket s=new ServerSocket(PORT);
System.out.println("Server Stared");
try
{
while(true)
{
Socket socket1=s.accept();
try
{
new Server3(socket1);
}
catch(Exception e)
{
socket1.close();
}
}
}
finally
{
s.close();
}
}
}

客户端程序:
import java.net.*;
import java.io.*;
public class Client3 extends Thread
{
int threadNumber;
Socket socket1;
public Client3(int i,Socket s)
{
System.out.println("Making thread="+i);
threadNumber=i;
socket1=s;
start();
}
public void run()
{
try
{
PrintWriter out=new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket1.getOutputStream())),true);
BufferedReader in=new BufferedReader(new InputStreamReader(socket1.getInputStream()));
for(int i=0;i<5;i++)
{
out.println("data from client:" + threadNumber + "=" + i);
//for(int i=0;i<5;i++)
String str=in.readLine();
System.out.println(str);
}
}
catch(IOException e)
{
try
{
socket1.close();
}
catch(IOException e2){}
}
}
public static void main(String[] args)throws IOException
{
for(int i=1;i<11;i++)
{
new Client3(i,new Socket(args[0],Integer.parseInt(args[1])));
//new Client3(2,new Socket(args[0],Integer.parseInt(args[1])));
}
}
}




话题树型展开
人气 标题 作者 字数 发贴时间
4471 请教:多线程Socket输出的意外 rjyang 2537 2005-03-08 16:38
3501 Re:请教:多线程Socket输出的意外 rjyang 92 2005-03-08 16:46

flat modethreaded modego to previous topicgo to next topicgo to back
  已读帖子
  新的帖子
  被删除的帖子
Jump to the top of page

   Powered by Jute Powerful Forum® Version Jute 1.5.6 Ent
Copyright © 2002-2021 Cjsdn Team. All Righits Reserved. 闽ICP备05005120号-1
客服电话 18559299278    客服信箱 714923@qq.com    客服QQ 714923