UINT SendThread(LPVOID param)
{
CWtTransportServerDlg *pDlg=(CWtTransportServerDlg*)AfxGetApp()->m_pMainWnd
CSocket ListenSocket
//创建一个socket来监听
if(!ListenSocket.Create(pDlg->m_nLocalPort+1,SOCK_DGRAM,"127.0.0.1"))
{
AfxMessageBox("监听端口失败!请重新指定!")
return 1
}
//创建发送socket
CSocket SendSocket
SendSocket.Create(0,SOCK_DGRAM/*,"127.0.0.1"*/)
CFile file(pDlg->m_strFilePath,CFile::modeRead)
//发送文件名
CString ip
UINT port
char buf[1024]
SendParam sp1
SendParam sp
do{
sp.cmd=START//设置命令
sprintf(sp.param,"%s",file.GetFileName())
SendSocket.SendTo((void*)&sp,sizeof(SendParam),pDlg->m_nReomtePort,pDlg->m_strIP)
pDlg->m_static1.SetWindowText("开始发送文件名")
ListenSocket.ReceiveFrom((void*)&sp1,sizeof(SendParam),ip,port)
}while(sp1.cmd!=sp.cmd)
//发送文件内容
int index=0
DWORD length=0
DWORD total=file.GetLength()
while(length<total)
{
sp.length=file.Read(buf,1024)
sp.cmd=BEGIN//设置命令
sp.index=index
memcpy(sp.param,buf,1024)
do{
SendSocket.SendTo((void*)&sp,sizeof(SendParam),pDlg->m_nReomtePort,pDlg->m_strIP)
pDlg->m_static1.SetWindowText("开始发送文件")
ListenSocket.ReceiveFrom((void*)&sp1,sizeof(SendParam),ip,port)//收到回应后接着发下一个数据块
}while(sp1.index!=sp.index)
index++
length+=sp.length
pDlg->m_progress1.SetPos(((int)length/total)*100)//更新进度条
}
//通知接收端文件发送结束
do{
sp.cmd=END//设置命令
SendSocket.SendTo((void*)&sp,sizeof(SendParam),pDlg->m_nReomtePort,pDlg->m_strIP)
pDlg->m_static1.SetWindowText("开始发送文件结束标志")
ListenSocket.ReceiveFrom((void*)&sp1,sizeof(SendParam),ip,port)
}while(sp1.index!=sp.index)
pDlg->m_progress1.SetPos(100)//更新进度条
file.Close()
return 0
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//接收线程
UINT ListenThread(LPVOID param)
{
while(1){
CWtTransportClientDlg *pDlg=(CWtTransportClientDlg*)AfxGetApp()->m_pMainWnd
CSocket ListenSocket
if(!ListenSocket.Create(pDlg->m_nLocalPort,SOCK_DGRAM/*,"127.0.0.1"*/))
{
AfxMessageBox("监听端口失败!请重新指定!")
return 1
}
CSocket SendSocket
SendSocket.Create(0,SOCK_DGRAM,"127.0.0.1")
CFile file
CString ip
UINT port
SendParam sp
do{
ListenSocket.ReceiveFrom((void*)&sp,sizeof(SendParam),ip,port)
if(sp.cmd==START){//收到文件名
file.Open(sp.param,CFile::modeCreate|CFile::modeWrite)//创建文件,准备接收
strcat(sp.param," 确认接收?")
AfxMessageBox(sp.param)//d出messagebox提醒用户接收文件,但实际上只是让客户知道而已
}
else if(sp.cmd==BEGIN){//如果是数据就写到文件里
file.Write(sp.param,sp.length)
}
SendSocket.SendTo((void*)&sp,sizeof(SendParam),pDlg->m_nReomtePort+1,ip)//收到数据块后发送反馈消息
}while(sp.cmd!=END)
file.Close()
}
return 0
}
程序分Server和Client服务器端打开侦听的端口,一有客户端连接就创建两个新的线程来负责这个连接
一个负责客户端发送的信息(ClientMsgCollectThread 类),
另一个负责通过该Socket发送数据(ServerMsgSendThread )
Server.java代码如下:
/*
* 创建日期 2009-3-7
*
* TODO 要更改此生成的文件的模板,请转至
* 窗口 - 首选项 - Java - 代码样式 - 代码模板
*/
package faue.MutiUser
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader
import java.io.PrintWriter
import java.net.ServerSocket
import java.net.Socket
/**
* 服务器端
*
* @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 = super.accept()
new Thread(new ClientMsgCollectThread(socket), "getAndShow"
+ socket.getPort()).start()
new Thread(new ServerMsgSendThread(socket), "send"
+ socket.getPort()).start()
}
} catch (IOException e) {
e.printStackTrace()
}
}
public static void main(String[] args) throws IOException {
new Server()
}
/**
* 该类用于创建接收客户端发来的信息并显示的线程
*
* @author Faue
* @version 1.0.0
*/
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 (!client.isClosed()) {
inputStringBuffer.delete(0, inputStringBuffer.length())
inputStringBuffer.append(in.readLine())
System.out.println(getMsg(inputStringBuffer.toString()))
}
} catch (IOException e) {
//e.printStackTrace()
System.out.println(client.toString() + " is closed!")
}
}
/**
* 构造显示的字符串
*
* @param line
* @return
*/
private String getMsg(String line) {
return client.toString() + " says:" + line
}
}
/**
* 该类用于创建发送数据的线程
*
* @author Faue
* @version 1.0.0
*/
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(client.getOutputStream(), true)
keyboardInput = new BufferedReader(new InputStreamReader(System.in))
}
public void run() {
try {
while (!client.isClosed()) {
outputStringBuffer.delete(0, outputStringBuffer.length())
outputStringBuffer.append(keyboardInput.readLine())
out.println(outputStringBuffer.toString())
}
} catch (IOException e) {
//e.printStackTrace()
System.out.println(client.toString() + " is closed!")
}
}
}
}
客户端:
实现基于IP地址的连接,连接后也创建两个线程来实现信息的发送和接收
/*
* 创建日期 2009-3-7
*
*/
package faue.MutiUser
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader
import java.io.PrintWriter
import java.net.Socket
/**
* 客户端
*
* @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"
+ mySocket.getPort()).start()
new Thread(new ClientMsgSendThread(mySocket), "send"
+ mySocket.getPort()).start()
} catch (IOException e) {
//e.printStackTrace()
System.out.println("Server.IP:" + IP
+ " port:10000 can not be Connected")
}
}
public static void main(String[] args) throws IOException {
try {
new Client(args[0])
} catch (Exception e) {
System.out.println("输入的IP地址错误")
}
}
/**
* 该类用于创建接收服务端发来的信息并显示的线程
*
* @author Faue
* @version 1.0.0
*/
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 (!client.isClosed()) {
inputStringBuffer.delete(0, inputStringBuffer.length())
inputStringBuffer.append(in.readLine())
System.out.println(getMsg(inputStringBuffer.toString()))
}
} catch (IOException e) {
//e.printStackTrace()
System.out.println(client.toString() + " is closed!")
System.exit(0)
}
}
/**
* 构造输入字符串
*
* @param line
* @return
*/
private String getMsg(String line) {
return client.toString() + " says:" + line
}
}
/**
* 该类用于创建发送数据的线程
*
* @author Faue
* @version 1.0.0
*/
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(client.getOutputStream(), true)
keyboardInput = new BufferedReader(new InputStreamReader(System.in))
}
public void run() {
try {
while (!client.isClosed()) {
outputStringBuffer.delete(0, outputStringBuffer.length())
outputStringBuffer.append(keyboardInput.readLine())
out.println(outputStringBuffer.toString())
}
out.println("--- See you, bye! ---")
} catch (IOException e) {
//e.printStackTrace()
System.out.println(client.toString() + " is closed!")
System.exit(0)
}
}
}
}
如果对您有帮助,请记得采纳为满意答案,谢谢!祝您生活愉快!
vaela
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)