用java多线程实现服务器与客户端之间的文件传输的代码!!!急!!!!
程序分Server和Client
服务器端打开侦听的端口,一有客户端连接就创建两个新的线程来负责这个连接
一个负责客户端发送的信息(ClientMsgCollectThread 类),
另一个负责通过该Socket发送数据(ServerMsgSendThread )
Serverjava代码如下:
/
创建日期 2009-3-7
TODO 要更改此生成的文件的模板,请转至
窗口 - 首选项 - Java - 代码样式 - 代码模板
/
package faueMutiUser;
import javaioBufferedReader;
import javaioIOException;
import javaioInputStreamReader;
import javaioPrintWriter;
import javanetServerSocket;
import javanetSocket;
/
服务器端
@author Faue
/
public class Server extends ServerSocket {
private static final int SERVER_PORT = 10000;
/
构造方法,用于实现连接的监听
@throws IOException
/
public Server() throws IOException {
super(SERVER_PORT);
try {
while (true) {
Socket socket = superaccept();
new Thread(new ClientMsgCollectThread(socket), "getAndShow"
+ socketgetPort())start();
new Thread(new ServerMsgSendThread(socket), "send"
+ socketgetPort())start();
}
} catch (IOException e) {
eprintStackTrace();
}
}
public static void main(String[] args) throws IOException {
new Server();
}
/
该类用于创建接收客户端发来的信息并显示的线程
@author Faue
@version 100
/
class ClientMsgCollectThread implements Runnable {
private Socket client;
private BufferedReader in;
private StringBuffer inputStringBuffer = new StringBuffer("Hello");
/
得到Socket的输入流
@param s
@throws IOException
/
public ClientMsgCollectThread(Socket s) throws IOException {
client = s;
in = new BufferedReader(new InputStreamReader(client
getInputStream(), "GBK"));
}
public void run() {
try {
while (!clientisClosed()) {
inputStringBufferdelete(0, inputStringBufferlength());
inputStringBufferappend(inreadLine());
Systemoutprintln(getMsg(inputStringBuffertoString()));
}
} catch (IOException e) {
//eprintStackTrace();
Systemoutprintln(clienttoString() + " is closed!");
}
}
/
构造显示的字符串
@param line
@return
/
private String getMsg(String line) {
return clienttoString() + " says:" + line;
}
}
/
该类用于创建发送数据的线程
@author Faue
@version 100
/
class ServerMsgSendThread implements Runnable {
private Socket client;
private PrintWriter out;
private BufferedReader keyboardInput;
private StringBuffer outputStringBuffer = new StringBuffer("Hello");
/
得到键盘的输入流
@param s
@throws IOException
/
public ServerMsgSendThread(Socket s) throws IOException {
client = s;
out = new PrintWriter(clientgetOutputStream(), true);
keyboardInput = new BufferedReader(new InputStreamReader(Systemin));
}
public void run() {
try {
while (!clientisClosed()) {
outputStringBufferdelete(0, outputStringBufferlength());
outputStringBufferappend(keyboardInputreadLine());
outprintln(outputStringBuffertoString());
}
} catch (IOException e) {
//eprintStackTrace();
Systemoutprintln(clienttoString() + " is closed!");
}
}
}
}
客户端:
实现基于IP地址的连接,连接后也创建两个线程来实现信息的发送和接收
/
创建日期 2009-3-7
/
package faueMutiUser;
import javaioBufferedReader;
import javaioIOException;
import javaioInputStreamReader;
import javaioPrintWriter;
import javanetSocket;
/
客户端
@author Faue
/
public class Client {
private Socket mySocket;
/
创建线程的构造方法
@param IP
@throws IOException
/
public Client(String IP) throws IOException {
try {
mySocket = new Socket(IP, 10000);
new Thread(new ServerMsgCollectThread(mySocket), "getAndShow"
+ mySocketgetPort())start();
new Thread(new ClientMsgSendThread(mySocket), "send"
+ mySocketgetPort())start();
} catch (IOException e) {
//eprintStackTrace();
Systemoutprintln("ServerIP:" + IP
+ " port:10000 can not be Connected");
}
}
public static void main(String[] args) throws IOException {
try {
new Client(args[0]);
} catch (Exception e) {
Systemoutprintln("输入的IP地址错误");
}
}
/
该类用于创建接收服务端发来的信息并显示的线程
@author Faue
@version 100
/
class ServerMsgCollectThread implements Runnable {
private Socket client;
private BufferedReader in;
private StringBuffer inputStringBuffer = new StringBuffer("Hello");
/
得到Socket的输入流
@param s
@throws IOException
/
public ServerMsgCollectThread(Socket s) throws IOException {
client = s;
in = new BufferedReader(new InputStreamReader(client
getInputStream(), "GBK"));
}
public void run() {
try {
while (!clientisClosed()) {
inputStringBufferdelete(0, inputStringBufferlength());
inputStringBufferappend(inreadLine());
Systemoutprintln(getMsg(inputStringBuffertoString()));
}
} catch (IOException e) {
//eprintStackTrace();
Systemoutprintln(clienttoString() + " is closed!");
Systemexit(0);
}
}
/
构造输入字符串
@param line
@return
/
private String getMsg(String line) {
return clienttoString() + " says:" + line;
}
}
/
该类用于创建发送数据的线程
@author Faue
@version 100
/
class ClientMsgSendThread implements Runnable {
private Socket client;
private PrintWriter out;
private BufferedReader keyboardInput;
private StringBuffer outputStringBuffer = new StringBuffer("Hello");
/
得到键盘的输入流
@param s
@throws IOException
/
public ClientMsgSendThread(Socket s) throws IOException {
client = s;
out = new PrintWriter(clientgetOutputStream(), true);
keyboardInput = new BufferedReader(new InputStreamReader(Systemin));
}
public void run() {
try {
while (!clientisClosed()) {
outputStringBufferdelete(0, outputStringBufferlength());
outputStringBufferappend(keyboardInputreadLine());
outprintln(outputStringBuffertoString());
}
outprintln("--- See you, bye! ---");
} catch (IOException e) {
//eprintStackTrace();
Systemoutprintln(clienttoString() + " is closed!");
Systemexit(0);
}
}
}
}
如果对您有帮助,请记得采纳为满意答案,谢谢!祝您生活愉快!
vaela
CS模式的QQ这是服务器:ChatServerjavaimport javanet;
import javaio;
public class ChatServer
{
final static int thePort=8189;
ServerSocket theServer;
ChatHandler[] chatters;
int numbers=0;
public static void main(String args[])
{
ChatServer app=new ChatServer();
apprun();
}
public ChatServer()
{
try
{
theServer=new ServerSocket(thePort);
chatters=new ChatHandler[10];
}
catch(IOException io){}
}
public void run()
{
try
{
Systemoutprintln("服务器已经建立!");
while(numbers<10)
{
Socket theSocket=theServeraccept();
ChatHandler chatHandler=new ChatHandler(theSocket,this);
chatters[numbers]=chatHandler;
numbers++;
}
}catch(IOException io){}
}
public synchronized void removeConnectionList(ChatHandler c)
{
int index=0;
for(int i=0;i<=numbers-1;i++)
if(chatters[i]==c)index=i;
for(int i=index;i<numbers-1;i++)
chatters[i]=chatters[i+1];
chatters[numbers-1]=null;
numbers--;
}
public synchronized String returnUsernameList()
{
String line="";
for(int i=0;i<=numbers-1;i++)
line=line+chatters[i]user+":";
return line;
}
public void broadcastMessage(String line)
{
Systemoutprintln("发布信息:"+line);
for(int i=0;i<=numbers-1;i++)
chatters[i]sendMessage(line);
}
}====================================================这是客户端:ChatClientjavaimport javaawt;
import javaawtevent;
import javaxswing;
import javanet;
import javaio;
public class ChatClient extends Thread implements ActionListener
{
JTextField messageField,IDField,ipField,portField;
JTextArea message,users;
JButton connect,disconnect;
String user="";
String userList[]=new String[10];
Socket theSocket;
BufferedReader in;
PrintWriter out;
boolean connected=false;
Thread thread;
public static void main(String args[])
{
JFrame frame=new JFrame("聊天室");
framesetDefaultCloseOperation(JFrameEXIT_ON_CLOSE);
ChatClient cc=new ChatClient();
JPanel content=cccreateComponents();
framegetContentPane()add(content);
framesetSize(550,310);
framesetVisible(true);
}
public JPanel createComponents()
{
JPanel pane=new JPanel(new BorderLayout());
message=new JTextArea(10,35);
messagesetEditable(false);
JPanel paneMsg=new JPanel();
paneMsgsetBorder(BorderFactorycreateTitledBorder("聊天内容"));
paneMsgadd(message);
users=new JTextArea(10,10);
JPanel listPanel=new JPanel();
listPanelsetBorder(BorderFactorycreateTitledBorder("在线用户:"));
listPaneladd(users);
messageField=new JTextField(50);
IDField=new JTextField(5);
ipField=new JTextField("LocalHost");
portField=new JTextField("8189");
connect=new JButton("连 接");
disconnect=new JButton("断 开");
disconnectsetEnabled(false);
JPanel buttonPanel=new JPanel();
buttonPaneladd(new Label("服务器IP:"));
buttonPaneladd(ipField);
buttonPaneladd(new Label("端口:"));buttonPaneladd(portField);
buttonPaneladd(new Label("用户名:"));
buttonPaneladd(IDField);
buttonPaneladd(connect);
buttonPaneladd(disconnect);
paneadd(messageField,"South");
paneadd(buttonPanel,"North");
paneadd(paneMsg,"Center");
paneadd(listPanel,"West");
connectaddActionListener(this);
disconnectaddActionListener(this);
messageFieldaddActionListener(this);
IDFieldaddActionListener(this);
ipFieldaddActionListener(this);
return pane;
}
public void actionPerformed(ActionEvent e)
{
if(egetSource()==connect){
user=IDFieldgetText();
String ip=ipFieldgetText();
int port =IntegerparseInt(portFieldgetText());
if(!userequals("")&&connectToServer(ip,port,user))
{
disconnectsetEnabled(true);
connectsetEnabled(false);
}
}
if(egetSource()==disconnect)disconnectFromServer();
if(egetSource()==messageField)
if(theSocket!=null)
{
outprintln("MESSAGE:"+messageFieldgetText());
messageFieldsetText("");
}
}
public void disconnectFromServer()
{
if(theSocket!=null)
{
try
{
connected=false;
outprintln("LEAVE:"+user);
disconnectsetEnabled(false);
connectsetEnabled(true);
thread=null;
theSocketclose();
}catch(IOException io){}
theSocket=null;
messagesetText("");
userssetText("");
}
}
public boolean connectToServer(String ip,int port,String ID)
{
if(theSocket!=null)
return false;
try
{
theSocket=new Socket(ip,port);
in=new BufferedReader(new InputStreamReader(theSocketgetInputStream()));
out=new PrintWriter(new OutputStreamWriter(theSocketgetOutputStream()),true);
outprintln("USER:"+user);
messagesetText("");
connected=true;
thread=new Thread(this);
threadstart();
}catch(Exception e){return false;}
return true;
}
public void extractMessage(String line)
{
Systemoutprintln(line);
Message messageline;
messageline=new Message(line);
if(messagelineisValid())
{
if(messagelinegetType()equals("JOIN"))
{
user=messagelinegetBody();
messageappend(user+"进入了聊天室\n");
}
else if(messagelinegetType()equals("LIST"))
updateList(messagelinegetBody());
else if(messagelinegetType()equals("MESSAGE"))
messageappend(messagelinegetBody()+"\n");
else if(messagelinegetType()equals("REMOVE"))
messageappend(messagelinegetBody()+"离开了聊天室\n");
}
else
messageappend("出现问题:"+line+"\n");
}
public void updateList(String line)
{
userssetText("");
String str=line;
for(int i=0;i<10;i++)
userList[i]="";
int index=strindexOf(":");
int a=0;
while(index!=-1){
userList[a]=strsubstring(0,index);
str=strsubstring(index+1);
a++;
index=strindexOf(":");
}
for(int i=0;i<10;i++)
usersappend(userList[i]+"\n");
}
public void run(){
try{
String line="";
while(connected && line!=null){
line=inreadLine();
if(line!=null) extractMessage(line);
}
}catch(IOException e){}
}
} =======================================================import javanet;
import javaio;
class ChatHandler extends Thread{
Socket theSocket;
BufferedReader in;
PrintWriter out;
int thePort;
ChatServer parent;
String user="";
boolean disconnect=false;
public ChatHandler(Socket socket,ChatServer parent){
try{
theSocket=socket;
thisparent=parent;
in=new BufferedReader(new InputStreamReader(theSocketgetInputStream()));
out=new PrintWriter(new OutputStreamWriter(theSocketgetOutputStream()),true);
thePort=theSocketgetPort();
start();
}catch(IOException io){}
}
public void sendMessage(String line){
outprintln(line);
}
public void setupUserName(String setname){
user=setname;
//Systemoutprint(user+"参加");
parentbroadcastMessage("JOIN:"+user);
}
public void extractMessage(String line){
Message messageline;
messageline = new Message(line);
if(messagelineisValid()){
if(messagelinegetType()equals("USER")){
setupUserName(messagelinegetBody());
parentbroadcastMessage("LIST:"+parentreturnUsernameList());
}
else if(messagelinegetType()equals("MESSAGE")){
parentbroadcastMessage("MESSAGE:"+user+"说: "+messagelinegetBody());
}
else if(messagelinegetType()equals("LEAVE")){
String c=disconnectClient();
parentbroadcastMessage("REMOVE:"+c);
parentbroadcastMessage("LIST:"+parentreturnUsernameList());
}
}
else
sendMessage("命令不存在!");
}
public String disconnectClient(){
try{
inclose();
outclose();
theSocketclose();
parentremoveConnectionList(this);
disconnect=true;
}catch(Exception ex){}
return user;
}
public void run(){
String line,name;
boolean valid=false;
try{
while((line=inreadLine())!=null){
Systemoutprintln("收到:"+line);
extractMessage(line);
}
}catch(IOException io){}
}
}
=========================================================
Messagejavapublic class Message{
private String type;
private String body;
private boolean valid;
public Message(String messageLine){
valid=false;
type=body=null;
int pos=messageLineindexOf(":");
if(pos>=0){
type=messageLinesubstring(0,pos)toUpperCase();
body=messageLinesubstring(pos+1);
valid=true;
}
}
public Message(String type,String body){
valid=true;
thistype=type;
thisbody=body;
}
public String getType(){
return type;
}
public String getBody(){
return body;
}
public boolean isValid(){
return valid;
}
} ==================================================共有4个文件,先运行服务段端。。。 这是我以前学的时候写过的!希望能帮的上你
服务器IP用:
echo(gethostbyname($SERVER_NAME));
客户端IP用下面函数:
function iptype1 () {
if (getenv("HTTP_CLIENT_IP")) {
return
getenv("HTTP_CLIENT_IP");
}
else {
return "none";
}
}
function iptype2 () {
if (getenv("HTTP_X_FORWARDED_FOR")) {
return getenv("HTTP_X_FORWARDED_FOR");
}
else {
return "none";
}
}
function iptype3 () {
if (getenv("REMOTE_ADDR")) {
return getenv("REMOTE_ADDR");
}
else {
return "none";
}
}
function ip() {
$ip1 = iptype1();
$ip2 = iptype2();
$ip3
= iptype3();
if (isset($ip1) && $ip1 != "none" && $ip1 !=
"unknown") {
return $ip1;
}
elseif (isset($ip2) && $ip2
!= "none" && $ip2 != "unknown") {
return $ip2;
}
elseif
(isset($ip3) && $ip3 != "none" && $ip3 != "unknown") {
return $ip3;
}
else {
return "none";
}
}
使用时,直接调用ip();
0条评论