load rom errcode 4=8是什么意思

的海词问答和网友补充:
相关词典网站:温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!&&|&&
人生一年又一年,只要每年都有所积累,有所成长,都有那么一次自己认为满意的花开时刻就好。即使一时不顺,也要敞开胸怀。生命的荣枯并不是简单的重复,一时的得失不是成败的尺度。花开不是荣耀,而是一个美丽的结束,花谢也不是耻辱,而是一个低调的开始。
LOFTER精选
: Microsoft Visual C++ .NET 2003
: Microsoft Visual C/C++ 6.0
: Borland C++Builder 6
: Intel, Compaq, or Digital Visual Fortran for Fortran MEX-files
Note: The LCC compiler shipped with MATLAB does not include a
debugger. You can use MEXPRINTF to print status messages to the screen, but will
not have access to breakpoints and controlled execution as with other compilers.
These instructions assume familiarity with your debugger.& For
instructions on how to use your debugger once the MEX-file is loaded, refer to
your debugger documentation.
Section 23: Debugging on Linux/UNIX/Mac You can find general Linux/UNIX/Mac debugging information here:
In addition, the MathWorks Support site contains step-by-step
instructions for the following debuggers:
: GDB for C
: GDB for Fortran
:&GDB and&DBX on numerous UNIX platforms. This includes platforms supported by
past versions of MATLAB.
:&GDB on Solaris
: Xcode on Mac
:&GDB for Fortran MEX-files&on Linux/UNIX/Mac These instructions assume familiarity with your debugger.& For
instructions on how to use your debugger once the MEX-file is loaded, refer to
your debugger documentation. Useful GDB commands
file Read a source file in
step Move forward one line in debugging
where, whereami&& Show the call stack, show the current location
list Show the current line and following source file contents
print Display the value of a variable
stop in, stop at Stop in a particular function, stop at a particular line
help Show the help
what Tell what a thing is, give the function prototype,
Section 24: Using other debuggers If using another debugger, start MATLAB with the -D flag, specifying your
matlab -Dgdb The GNU debugger
matlab -Dddd A graphical front end to GDB
matlab -D"workshop -D &path to matlab.exe&"& The Sun Workshop debugger Section 25: C++ MEX-file Overview MEX-files can be written in C++. See mexcpp.cpp in the
$MATLABROOT/extern/examples/mex directory (where
$MATLABROOT is the MATLAB root directory on your machine, as returned
by typing matlabroot at the MATLAB Command Prompt.)
Section 26: Tips for C++ MEX-files Here are some tips to keep in mind if you decide to use C++ in your
For an example MEX-file, see:
&MATLAB&/extern/examples/mex/mexcpp.cppThe
extension .cpp is unambiguous and generally recognized by C++ compilers. Other
possible extensions include .C, .cc, and .cxx.
Using cout will not work as expected in C++ MEX-files. This is because cout
is expecting to use a display that is not MATLAB. To workaround this problem,
If you run your MEX-file in MATLAB and you do not receive the expected
output, make sure that you have a C++ flush() function call in your
Section 27: Compiling C++ MEX-filesUse mex -setupto select a C++ compiler at the MATLAB command
prompt. The LCC compiler shipped with MATLAB is a C-only compiler, and cannot be
used with C++. Next, invoke MEX as:
mex mexcpp.cpp Special instructions for MATLAB 6.1 (R12.1) and earlier on
UNIX: In order to compile this example, you should copy the options
file for C++ MEX-files (&MATLAB&/bin/cxxopts.sh) to your current
directory. Then, invoke MEX as:mex mexcpp.cpp -f cxxopts.shThis is not required for
MATLAB 6.5 (R13) and later on UNIX, where a C++ compiler can be selected using
mex -setup as shown above.
Section 28: If Linking fails
Retry compiling withyprime.c Try runningmex -setupagain
Check that you are using a supported compiler. A list of supported compilers
can be found in the .
Verify that the code is correct C code
If you are getting linking, unresolved external, or undefined symbols
errors, follow these steps:
Find the name of the symbol
It is a MathWorks symbol? Does it begin with "_mx", "_mex", "_eng","_mat",
"_mlf", or "_mcl"?
If it is a MathWorks symbol, ensure you are linking aganist the correct
Section 29: If loading fails
Dependency Walker is a free tool that can help identify missing DLL-files,
one common cause of MEX-files that fail to load on Windows. Solution
explains how to use Dependency Walker to diagnose this issue.
Ensure the MEX-file is a 32- or 64-bit shared library as appropriate for
your platform. In particular, Windows MEX-files cannot depend on 16-bit
libraries.
Ensure &MATLAB&/extern/lib/$ARCH is included in $LD_LIBRARY_PATH
Messages from ld.so usually indicate a problem with the library
On Windows, ensure that the directories of all necessary external DLL-files
are in the PATH variable
Section 30: If running fails - segmentation violations: Memory is grouped into blocks, or segments. A key function of every operating
system is to keep track of which processes own the various memory segments. A
process can only access memory which it owns. This prevents critical data from
being overwritten and maintains security. A segmentation violation occurs when a process attempts to access memory
which it does not own. This typically happens when a user tries to write past
the end of an array, access dynamically allocated data that has previously been
freed, or de-reference a NULL pointer. If you encounter a problem like this, debug the MEX-file using the steps in
the .&Table of MEX Examples Source code for the MEX examples shown in the following table are in
subfolders of matlabroot/extern/examples. For more
information, see
or , or enter the example name in the Help browser search field. MEX Examples
Example Name
Example Subfolder
Description
refbook Fill mxArray using mxGetPr
refbook Fill mxArray with non-double values
refbook Fill mxArray using mxSetPr to dynamically
allocate memory
mex Multiply a scalar times 1xN matrix
mex Illustrate memory requirements of large
refbook Pass complex data
refbook Use of Fortran %VAL
refbook Handle FORTRAN complex return type for function called from
a C MEX-file
refbook Use unsigned 16-bit integers
mex Identify data type of input variable
refbook Use N-dimensional arrays
refbook Populate a sparse matrix
refbook Call a LAPACK function
refbook Call a LAPACK function with complex numbers
refbook Call a BLAS function
refbook Pass matrices in Fortran
refbook Pass non-double matrices in Fortran
mex Register an exit function to close a data file
mex Call built-in MATLABdisp function
mex Illustrate some C++ language features in a
mex Use mexEvalString to assign variables in
mex How to use mexfunction
mex Use mexGet and mexSet to change
Color property of a graphics handle
mex Use mexGetVariable and mexPutVariable to
track counters in the MEX-file and in the MATLAB global workspace
mex How to lock and unlock a MEX-file
mex Control MATLAB response to errors in
mexCallMATLAB
mx Demonstrate MATLAB 1-based matrix indexing versus C 0-based
mx Create 2-D cell array
mx Create 2-D string array
mx Create MATLAB structure from C structure
mx Read MATLABeps value
mx Read inf value
mx Display number of nonzero elements in a sparse matrix and
maximum number of nonzero elements it can store
mx Check if array is member of specified class
mx Check for NaN and infinite values
mx Check if workspace variable is logical or global
mx Allocate memory to copy a MATLAB string to a C
mx Reshape an array
mx Reallocate memory for sparse matrix and reset values of
pr, pi, ir and nzmax
refbook Pass C character matrix from FORTRAN to MATLAB
refbook Manipulate structures and cell arrays
refbook Copy MATLAB string data to and from C-style string
refbook Create mxArray and pass to MATLABsin and
plot functions
refbook Demonstrate common workflow of MEX-file
refbook Use LAPACK for symmetric indefinite factorization
refbook Pass multiple parameters
refbook Solve simple 3 body orbit problem
阅读(2225)|
用微信&&“扫一扫”
将文章分享到朋友圈。
用易信&&“扫一扫”
将文章分享到朋友圈。
历史上的今天
在LOFTER的更多文章
loftPermalink:'',
id:'fks_082',
blogTitle:'什么是Mex文件?Using MEX-Files to Call C/C++ Programs',
blogAbstract:'Mex文件其实就是用C语言写好的函数,编译后能被MATLAB调用。编译完成后,即可像m文件一样适用mex。Using MEX-Files to Call C/C++ and Fortran
ProgramsIntroduction
{if x.moveFrom=='wap'}
{elseif x.moveFrom=='iphone'}
{elseif x.moveFrom=='android'}
{elseif x.moveFrom=='mobile'}
${a.selfIntro|escape}{if great260}${suplement}{/if}
{list a as x}
推荐过这篇日志的人:
{list a as x}
{if !!b&&b.length>0}
他们还推荐了:
{list b as y}
转载记录:
{list d as x}
{list a as x}
{list a as x}
{list a as x}
{list a as x}
{if x_index>4}{break}{/if}
${fn2(x.publishTime,'yyyy-MM-dd HH:mm:ss')}
{list a as x}
{if !!(blogDetail.preBlogPermalink)}
{if !!(blogDetail.nextBlogPermalink)}
{list a as x}
{if defined('newslist')&&newslist.length>0}
{list newslist as x}
{if x_index>7}{break}{/if}
{list a as x}
{var first_option =}
{list x.voteDetailList as voteToOption}
{if voteToOption==1}
{if first_option==false},{/if}&&“${b[voteToOption_index]}”&&
{if (x.role!="-1") },“我是${c[x.role]}”&&{/if}
&&&&&&&&${fn1(x.voteTime)}
{if x.userName==''}{/if}
网易公司版权所有&&
{list x.l as y}
{if defined('wl')}
{list wl as x}{/list}AMD&OpenCL大学课程(8):OpenCL&buffer使用及两个简单例子
在本节,我们主要介绍OpenCL中buffer的使用,同时提供了2个完整的例子,一个是图像的旋转,一个是矩阵乘法(非常简单,没有分块优化)。
1、创建OpenCL设备缓冲(buffer)
OpenCL设备使用的数据都存放在设备的buffer中[其实就是device
memory中]。我们用下面的代码创建buffer对象:
cl_mem bufferobj = clCreateBuffer (
cl_context context, //Context name
cl_mem_flags flags, //Memory flags
size_t size, //Memory size allocated in buffer
void *host_ptr, //Host data
cl_int *errcode) //Returned error code
如果host_ptr指向一个有效的host指针,则创建一个buffer对象的同时会实现隐式的数据拷贝(会在kernel函数进入队列时候,把host_prt中的数据从host
memory拷贝到设备内存对象bufferobj中)。
我们可以通过flags参数指定buffer对象的属性。
函数clEnqueueWriteBuffer()用来实现显示的数据拷贝,即把host
memory中的数据拷贝到device meomory中。
cl_int clEnqueueWriteBuffer (
cl_command_queue queue, //Command queue to device
cl_mem buffer, //OpenCL Buffer Object
cl_bool blocking_read, //Blocking/Non-Blocking Flag
size_t offset, //Offset into buffer to write to
size_t cb, //Size of data
void *ptr, //Host pointer
cl_uint num_in_wait_list, //Number of events in wait list
const cl_event * event_wait_list, //Array of events to wait for
cl_event *event) //Event handler for this function
2、图像旋转的例子
下面是一个完整的OpenCL例子,实现图像的旋转。在这个例子中,我把美丽的lenna旋转了90度。
下面是原始图像和旋转后的图像(黑白)
在这个例子中,我使用FreeImage库,可以从FreeImage网站或者我的code工程中下载。
图像旋转是指把定义的图像绕某一点以逆时针或顺时针方向旋转一定的角度,通常是指绕图像的中心以逆时针方向旋转。
假设图像的左上角为(left, top),右下角为(right, bottom),则图像上任意点(x0,
y0)绕其中心(xcenter, ycenter)逆时针旋转angle角度后,新的坐标位置(x&, y&)的计算公式为:
xcenter = (right - left + 1) / 2 +
ycenter = (bottom - top + 1) / 2 +
x& = (x0 - xcenter) cosθ - (y0 - ycenter) sinθ +
y& = (x0 - xcenter) sinθ + (y0 - ycenter) cosθ +
下面给出kernel的代码:
&1:&__kernel&void&image_rotate(
__global uchar * src_data, __global uchar *
dest_data,&//Data in global memory
2: int W, int H, //Image Dimensions
3: float sinTheta, float cosTheta ) //Rotation Parameters
5: //Thread gets its index within index space
6: const int ix = get_global_id(0);
7: const int iy = get_global_id(1);
9: int xc = W/2;
10: int yc = H/2;
12: int xpos = ( ix-xc)*cosTheta - (iy-yc)*sinTheta+
13: int ypos = (ix-xc)*sinTheta + ( iy-yc)*cosTheta+
15: if ((xpos&=0) && (xpos& W) && (ypos&=0) && (ypos& H)) //Bound Checking
17: dest_data[ypos*W+xpos]= src_data[iy*W+ix];
src_data为原始图像(灰度图)数据,dest_data为旋转后的图像数据。W、H分别为图像的高度和宽度。sinTheta和cosTheta是旋转参数。我在代码中实现了旋转90度,所以sinTheta为1,cosTheta为0,大家可以尝试其它的值。
下面是程序的流程图:
在前面向量加法的例子中,我已经介绍了OpenCL一些基本的步骤。
创建platform对象
创建GPU设备
创建contex
创建命令队列
创建缓冲对象,代码如下:
1: cl_mem d_ip = clCreateBuffer(
2: context, CL_MEM_READ_ONLY,
3: mem_size,
4: NULL, NULL);
5: l_mem d_op = clCreateBuffer(
6: context, CL_MEM_WRITE_ONLY,
7: mem_size,
8: NULL, NULL);
9: status = clEnqueueWriteBuffer (
10: queue , d_ip, CL_TRUE,
11: 0, mem_size, (void *)src_image,
12: 0, NULL, NULL);
创建程序对象
编译程序对象
创建Kernel对象
设置kernel参数
执行kernel
数据拷贝回host memory,我采用映射memory的方式。
1: unsigned char *op_data=0;
2: //op_data =(unsigned char *)malloc(mem_size);
3: status = clEnqueueReadBuffer(
4: //queue, d_op,
5: //CL_TRUE, //Blocking Read Back
6: //0, mem_size,(void*)op_data, NULL, NULL, NULL);
7: op_data = (cl_uchar *) clEnqueueMapBuffer( queue,
9: CL_TRUE,
10: CL_MAP_READ,
12: mem_size,
13: 0, NULL, NULL, NULL );
kernel执行时间的计算后面教程会有详细介绍,但在本节中,我们会给出通过事件机制来得到kernel执行时间,首先要在创建队列时候,使用CL_QUEUE_PROFILING_ENABLE参数,否则计算的kernel运行时间是0。
下面是代码:
1: //计算kerenl执行时间
2: cl_ulong startTime, endT
clGetEventProfilingInfo(ev, CL_PROFILING_COMMAND_START,
4: sizeof(cl_ulong), &startTime, NULL);
5: clGetEventProfilingInfo(ev, CL_PROFILING_COMMAND_END,
6: sizeof(cl_ulong), &endTime, NULL);
7: cl_ulong kernelExecTimeNs = endTime-startT
8: printf("kernal exec time :%8.6f ms\n ", kernelExecTimeNs*1e-6 );
完整的程序代码:
1: #include "stdafx.h"
2: #include
3: #include
4: #include
5: #include
6: #include
7: #include
9: #include "gFreeImage.h"
11: using namespace
12: #define NWITEMS 4
13: #pragma comment (lib,"OpenCL.lib")
14: #pragma comment(lib,"FreeImage.lib")
16: //把文本文件读入一个string中
17: int convertToString(const char *filename, std::string& s)
22: std::fstream f(filename, (std::fstream::in | std::fstream::binary));
24: if(f.is_open())
26: size_t fileS
27: f.seekg(0, std::fstream::end);
28: size = fileSize = (size_t)f.tellg();
29: f.seekg(0, std::fstream::beg);
31: str = new char[size+1];
32: if(!str)
34: f.close();
35: return NULL;
38: f.read(str, fileSize);
39: f.close();
40: str[size] = '\0';
43: delete[]
44: return 0;
46: printf("Error: Failed to open file %s\n", filename);
47: return 1;
50: //CPU旋转图像
&51:&void&cpu_rotate(unsigned&char*
inbuf,&unsigned&char*
outbuf,&int&w,&int&h,float&sinTheta,float&cosTheta)
53: int i,
54: int xc = w/2;
55: int yc = h/2;
57: for(i = 0; i & i++)
59: for(j=0; j& j++)
61: int xpos = ( j-xc)*cosTheta - (i-yc)*sinTheta+
62: int ypos = (j-xc)*sinTheta + ( i-yc)*cosTheta+
64: if(xpos&=0&&ypos&=0&&xpos
65: outbuf[ypos*w + xpos] = inbuf[i*w+j];
70: int main(int argc, char* argv[])
72: //装入图像
73: unsigned char *src_image=0;
74: unsigned char *cpu_image=0;
75: int W, H;
76: gFreeI
77: if(!img.LoadImageGrey("lenna.jpg"))
79: printf("装入lenna.jpg失败\n");
80: exit(0);
83: src_image = img.getImageDataGrey(W, H);
85: size_t mem_size = W*H;
86: cpu_image = (unsigned char*)malloc(mem_size);
89: cl_platform_
91: //创建平台对象
92: status = clGetPlatformIDs( 1, &platform, NULL );
94: cl_device_
96: //创建GPU设备
97: clGetDeviceIDs( platform, CL_DEVICE_TYPE_GPU,
99: &device,
100: NULL);
101: //创建context
102: cl_context context = clCreateContext( NULL,
104: &device,
105: NULL, NULL, NULL);
106: //创建命令队列
107: cl_command_queue queue = clCreateCommandQueue( context,
108: device,
109: CL_QUEUE_PROFILING_ENABLE, NULL );
111: //创建三个OpenCL内存对象,并把buf1的内容通过隐式拷贝的方式
112: //拷贝到clbuf1,buf2的内容通过显示拷贝的方式拷贝到clbuf2
113: cl_mem d_ip = clCreateBuffer(
114: context, CL_MEM_READ_ONLY,
115: mem_size,
116: NULL, NULL);
117: cl_mem d_op = clCreateBuffer(
118: context, CL_MEM_WRITE_ONLY,
119: mem_size,
120: NULL, NULL);
121: status = clEnqueueWriteBuffer (
122: queue , d_ip, CL_TRUE,
123: 0, mem_size, (void *)src_image,
124: 0, NULL, NULL);
126: const char * filename = "rotate.cl";
127: std::string sourceS
128: status = convertToString(filename, sourceStr);
129: const char * source = sourceStr.c_str();
130: size_t sourceSize[] = { strlen(source) };
132: //创建程序对象
133: cl_program program = clCreateProgramWithSource(
134: context,
136: &source,
137: sourceSize,
138: NULL);
139: //编译程序对象
140: status = clBuildProgram( program, 1, &device, NULL, NULL, NULL );
141: if(status != 0)
143: printf("clBuild failed:%d\n", status);
144: char tbuf[0x10000];
145: clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG, 0x10000, tbuf, NULL);
146: printf("\n%s\n", tbuf);
147: return -1;
151: //创建Kernel对象
152: //Use the “image_rotate” function as the kernel
154: //创建Kernel对象
155: cl_kernel kernel = clCreateKernel( program, "image_rotate", NULL );
157: //设置Kernel参数
158: float sintheta = 1, costheta = 0;
159: clSetKernelArg(kernel, 0, sizeof(cl_mem), (void *)&d_ip);
160: clSetKernelArg(kernel, 1, sizeof(cl_mem), (void *)&d_op);
161: clSetKernelArg(kernel, 2, sizeof(cl_int), (void *)&W);
162: clSetKernelArg(kernel, 3, sizeof(cl_int), (void *)&H);
163: clSetKernelArg(kernel, 4, sizeof(cl_float), (void *)&sintheta);
164: clSetKernelArg(kernel, 5, sizeof(cl_float), (void *)&costheta);
166: //Set local and global workgroup sizes
167: size_t localws[2] = {16,16} ;
168: size_t globalws[2] = {W, H};//Assume divisible by 16
171: //执行kernel
172: clEnqueueNDRangeKernel(
173: queue ,kernel,
174: 2, 0, globalws, localws,
175: 0, NULL, &ev);
177: clFinish( queue );
179: //计算kerenl执行时间
180: cl_ulong startTime, endT
181: clGetEventProfilingInfo(ev, CL_PROFILING_COMMAND_START,
182: sizeof(cl_ulong), &startTime, NULL);
183: clGetEventProfilingInfo(ev, CL_PROFILING_COMMAND_END,
184: sizeof(cl_ulong), &endTime, NULL);
185: cl_ulong kernelExecTimeNs = endTime-startT
186: printf("kernal exec time :%8.6f ms\n ", kernelExecTimeNs*1e-6 );
188: //数据拷回host内存
189: // copy results from device back to host
190: unsigned char *op_data=0;
191: //op_data =(unsigned char *)malloc(mem_size);
192: // status = clEnqueueReadBuffer(
193: //queue, d_op,
194: //CL_TRUE, //Blocking Read Back
195: //0, mem_size,(void*)op_data, NULL, NULL, NULL);
196: op_data = (cl_uchar *) clEnqueueMapBuffer( queue,
197: d_op,
198: CL_TRUE,
199: CL_MAP_READ,
201: mem_size,
202: 0, NULL, NULL, NULL );
205: cpu_rotate(src_image,cpu_image, W, H, 1, 0);
206: for(i = 0; i & mem_ i++)
208: src_image[i] =cpu_image[i];
210: img.SaveImage("cpu_lenna_rotate.jpg");
211: for(i = 0; i & mem_ i++)
213: src_image[i] =op_data[i];
215: img.SaveImage("lenna_rotate.jpg");
217: if(cpu_image)
218: free(cpu_image);
220: //删除OpenCL资源对象
221: clReleaseMemObject(d_ip);
222: clReleaseMemObject(d_op);
223: clReleaseProgram(program);
224: clReleaseCommandQueue(queue);
225: clReleaseContext(context);
226: return 0;
感兴趣的朋友可以从下载完整代码。
注意代码运行后,会在程序目录生成lenna_rotate.jpg,这时gpu执行的结果,另外还有一个cpu_lenna_rotate.jpg这是CPU执行的结果。
3、一个矩阵乘法的例子
在amd的slides中,本节还讲了一个简单的,没有优化的矩阵乘法,一共才2两页ppt,所以我也不在这儿详细讲述了,…,但简单介绍还是需要的。
1: for(int i = 0; i & Ha; i++)
2: for(int j = 0; j & Wb; j++){
3: c[i][j] = 0;
4: for(int k = 0; k & Wa; k++)
5: c[i][j] += a[i][k] + b[k][j]
上面的代码是矩阵乘法的例子,有三重循环,下面我们只给出kernel代码,完整程序请从:下载。
<font COLOR="#:&__kernel&void&simpleMultiply(
2: __global float* c, int Wa, int Wb,
3: __global float* a, __global float* b)
6: //Get global position in Y direction
7: int row = get_global_id(1);
8: //Get global position in X direction
9: int col = get_global_id(0);
10: float sum = 0.0f;
11: //Calculate result of one element
12: for (int i = 0; i & Wa; i++)
14: sum +=
15: a[row*Wa+i] * b[i*Wb+col];
17: c[row*Wb+col] =
原文作者:迈克老狼
已投稿到:
以上网友发言只代表其个人观点,不代表新浪网的观点或立场。青乡之b 的BLOG
用户名:青乡之b
文章数:17
访问量:12252
注册日期:
阅读量:4305
51CTO推荐博文
&#include&&stdio.h& &#include&&winsock2.h&&&&&&&&&&&&&&//winsock.h&(2种套接字版本) &#pragma&comment(lib,&ws2_32.lib&)&//wsock32.lib &&#define&MAXSIZE&100&// &&int&main() &{ &&&&&&&&&&int&retV &&&&&&char&buf[MAXSIZE]; &&&&&&&&&&&WORD&wVersionR &&&&&WSADATA& &&&&&&wVersionRequest=MAKEWORD(2,2); &&&&&&retVal=WSAStartup(wVersionRequest,&wsadata); &&&&&if(retVal&==&SOCKET_ERROR) &&&&&{ &&&&&&&&&printf(&WSAStartup&failed!&); &&&&&&&&&&return&-1; &&&&&} &&&&&&&&&&&SOCKET&sS &&&&&sServer=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP); &&&&&if(sServer&==&INVALID_SOCKET) &&&&&{ &&&&&&&&&printf(&socket&failed!&); &&&&&&&&&&WSACleanup(); &&&&&&&&&return&-1;&&&&&&} &&&&&&&&&&&int&imode=1; &&&&&retVal=ioctlsocket(sServer,FIONBIO,(u_long&*)&imode); &&&&&if(retVal&==&SOCKET_ERROR) &&&&&{ &&&&&&&&&printf(&ioctlsocket&failed!&); &&&&&&&&&&closesocket(sServer); &&&&&&&&&WSACleanup(); &&&&&&&&&return&-1; &&&&&} &&&&&&&&&&&SOCKADDR_IN&addrS &&&&&addrServ.sin_family=AF_INET; &&&&&addrServ.sin_port&&=htons(5000); &&&&&addrServ.sin_addr.S_un.S_addr=inet_addr(&192.168.0.102&); &&&&&&retVal=bind(sServer,(SOCKADDR&*)&addrServ,sizeof(addrServ));&&&&&&if(retVal&==&SOCKET_ERROR) &&&&&{ &&&&&&&&&printf(&bind&failed!&); &&&&&&&&&&closesocket(sServer); &&&&&&&&&WSACleanup(); &&&&&&&&&return&-1; &&&&&} &&&&&&retVal=listen(sServer,1);&&&&&&if(retVal&==&SOCKET_ERROR) &&&&&{ &&&&&&&&&printf(&listen&failed!&); &&&&&&&&&&closesocket(sServer); &&&&&&&&&WSACleanup(); &&&&&&&&&return&-1; &&&&&} &&&&&&&&&&&&sockaddr_in&addrC&&&&&&int&len=sizeof(sockaddr_in); &&&&&&SOCKET&sC &&&&&int& &&&&&&while(true) &&&&&{ &&&&&&&&&sClient=accept(sServer,(sockaddr&*)&addrClient,&len); &&&&&&&&&if(sClient&==&INVALID_SOCKET) &&&&&&&&&{ &&&&&&&&&&&&&errcode=WSAGetLastError(); &&&&&&&&&&&&&if(errcode&==&WSAEWOULDBLOCK)&&&&&&&&&&&&&&&{ &&&&&&&&&&&&&&&&&Sleep(100); &&&&&&&&&&&&&&&&&continue; &&&&&&&&&&&&&} &&&&&&&&&&&&&else&&&&&&&&&&&&&{ &&&&&&&&&&&&&&&&&printf(&accept&failed!&); &&&&&&&&&&&&&&&&&&closesocket(sServer);&&&&&&&&&&&&&&&&&&WSACleanup();&&&&&&&&&&&&&&&&&&return&-1; &&&&&&&&&&&&&} &&&&&&&&&} &&&&&&&&&&break;&&&&&&} &&&&&&&&&&&while(true) &&&&&{ &&&&&&&&&retVal=recv(sClient,buf,strlen(buf),0); &&&&&&&&&if(retVal&==&SOCKET_ERROR) &&&&&&&&&{ &&&&&&&&&&&&&errcode=WSAGetLastError();&&&&&&&&&&&&&&if(errcode&==&WSAEWOULDBLOCK)&&&&&&&&&&&&&&&{ &&&&&&&&&&&&&&&&&Sleep(100); &&&&&&&&&&&&&&&&&continue; &&&&&&&&&&&&&} &&&&&&&&&&&&&else&&&&&&&&&&&&&{ &&&&&&&&&&&&&&&&&if(errcode==WSAETIMEDOUT&||&errcode==WSAENETDOWN) &&&&&&&&&&&&&&&&&{ &&&&&&&&&&&&&&&&&&&&&closesocket(sClient); &&&&&&&&&&&&&&&&&&&&&closesocket(sServer); &&&&&&&&&&&&&&&&&&&&&WSACleanup(); &&&&&&&&&&&&&&&&&&&&&return&-1; &&&&&&&&&&&&&&&&&} &&&&&&&&&&&&&} &&&&&&&&&} &&&&&&&&&&if(buf&==&&quit&)&&&&&&&&&&{ &&&&&&&&&&&&&retVal=send(sClient,buf,strlen(buf),0); &&&&&&&&&&&&&break; &&&&&&&&&} &&&&&&&&&else&&&&&&&&&{ &&&&&&&&&&&&&&&&&&&&&&&&&&while(true) &&&&&&&&&&&&&{ &&&&&&&&&&&&&&&&&retVal=send(sClient,buf,strlen(buf),0);&&&&&&&&&&&&&&&&&&if(retVal&==&SOCKET_ERROR)&&&&&&&&&&&&&&&&&&&{ &&&&&&&&&&&&&&&&&&&&&errcode=WSAGetLastError(); &&&&&&&&&&&&&&&&&&&&&if(errcode&==&WSAEWOULDBLOCK)&&&&&&&&&&&&&&&&&&&&&&&{ &&&&&&&&&&&&&&&&&&&&&&&&&Sleep(100); &&&&&&&&&&&&&&&&&&&&&&&&&continue; &&&&&&&&&&&&&&&&&&&&&} &&&&&&&&&&&&&&&&&&&&&else&&&&&&&&&&&&&&&&&&&&&{ &&&&&&&&&&&&&&&&&&&&&&&&&closesocket(sClient); &&&&&&&&&&&&&&&&&&&&&&&&&closesocket(sServer); &&&&&&&&&&&&&&&&&&&&&&&&&WSACleanup(); &&&&&&&&&&&&&&&&&&&&&&&&&return&-1; &&&&&&&&&&&&&&&&&&&&&&} &&&&&&&&&&&&&&&&&} &&&&&&&&&&&&&&&&&&break;&&&&&&&&&&&&&&} &&&&&&&&&&} &&&&&} &&}&
&#include&&stdio.h& &#include&&WinSock2.h&&//winsock.h &#pragma&comment(lib,&ws2_32.lib&);&//wsock32.lib &&#include&&iostream& &using&namespace& &&#include&&string.h&&//strcpy函数 &&#define&MAXSIZE&100&// &&int&main() &{ &&&&&&&&&&int&retV &&&&&&char&buf[MAXSIZE]; &&&&&&&&&&&WORD&wVersionR &&&&&WSADATA& &&&&&&wVersionRequest=MAKEWORD(2,2); &&&&&&retVal=WSAStartup(wVersionRequest,&wsadata); &&&&&if(retVal&==&SOCKET_ERROR) &&&&&{ &&&&&&&&&printf(&WSAStartup&failed!&); &&&&&&&&&&return&-1; &&&&&} &&&&&&&&&&&SOCKET&sC &&&&&sClient=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP); &&&&&if(sClient&==&INVALID_SOCKET) &&&&&{ &&&&&&&&&printf(&socket&failed!&); &&&&&&&&&&WSACleanup(); &&&&&&&&&return&-1;&&&&&&} &&&&&&&&&&&int&imode=1; &&&&&retVal=ioctlsocket(sClient,FIONBIO,(u_long&*)&imode); &&&&&if(retVal&==&SOCKET_ERROR) &&&&&{ &&&&&&&&&printf(&ioctlsocket&failed!&); &&&&&&&&&&closesocket(sClient); &&&&&&&&&WSACleanup(); &&&&&&&&&return&-1; &&&&&} &&&&&&&&&&&&sockaddr_in&addrS &&&&&addrServ.sin_family=AF_INET;&&&&&&addrServ.sin_port&&=htons(5000);&&&&&&addrServ.sin_addr.S_un.S_addr=inet_addr(&192.168.0.102&); &&&&&&int&len=sizeof(sockaddr_in);&&&&&&&while(true) &&&&&{ &&&&&&&&&retVal=connect(sClient,(sockaddr&*)&addrServ,len);&&&&&&&&&&if(retVal&==&INVALID_SOCKET) &&&&&&&&&{ &&&&&&&&&&&&&int&errcode=WSAGetLastError(); &&&&&&&&&&&&&if(errcode==WSAEWOULDBLOCK&||&errcode==WSAEINVAL)&&&&&&&&&&&&&&&{ &&&&&&&&&&&&&&&&&Sleep(100); &&&&&&&&&&&&&&&&&continue; &&&&&&&&&&&&&} &&&&&&&&&&&&&else&&&&&&&&&&&&&{ &&&&&&&&&&&&&&&&&if(errcode&==&WSAEISCONN)&&&&&&&&&&&&&&&&&&{ &&&&&&&&&&&&&&&&&&&&&break;& &&&&&&&&&&&&&&&&&} &&&&&&&&&&&&&&&&&else&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&{ &&&&&&&&&&&&&&&&&&&&&printf(&connect&failed!&); &&&&&&&&&&&&&&&&&&&&&&closesocket(sClient);& &&&&&&&&&&&&&&&&&&&&&WSACleanup();&&&&&&&&&&&&&&&&&&&&&&return&-1; &&&&&&&&&&&&&&&&&} &&&&&&&&&&&&&&} &&&&&&&&&} &&&&&&} &&&&&&&&&&&while(true) &&&&&{ &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&strcpy(buf,&Hello&TCP!&); &&&&&&&&&&retVal=send(sClient,buf,strlen(buf),0);&&&&&&&&&&if(retVal&==&SOCKET_ERROR)&&&&&&&&&&&{ &&&&&&&&&&&&&int&errcode=WSAGetLastError(); &&&&&&&&&&&&&if(errcode&==&WSAEWOULDBLOCK)&&&&&&&&&&&&&&&{ &&&&&&&&&&&&&&&&&Sleep(100); &&&&&&&&&&&&&&&&&continue; &&&&&&&&&&&&&} &&&&&&&&&&&&&else&&&&&&&&&&&&&{ &&&&&&&&&&&&&&&&&printf(&send&failed!&); &&&&&&&&&&&&&&&&&&closesocket(sClient); &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&WSACleanup(); &&&&&&&&&&&&&&&&&return&-1; &&&&&&&&&&&&&&} &&&&&&&&&} &&&&&&&&&&break;&&&&&&} &&&&&&&&&&&while(true) &&&&&{ &&&&&&&&&retVal=recv(sClient,buf,strlen(buf),0); &&&&&&&&&if(retVal&==&SOCKET_ERROR) &&&&&&&&&{ &&&&&&&&&&&&&int&errcode=WSAGetLastError();&&&&&&&&&&&&&&if(errcode&==&WSAEWOULDBLOCK)&&&&&&&&&&&&&&&{ &&&&&&&&&&&&&&&&&Sleep(100); &&&&&&&&&&&&&&&&&continue; &&&&&&&&&&&&&} &&&&&&&&&&&&&else&&&&&&&&&&&&&{ &&&&&&&&&&&&&&&&&if(errcode==WSAETIMEDOUT&||&errcode==WSAENETDOWN) &&&&&&&&&&&&&&&&&{ &&&&&&&&&&&&&&&&&&&&&printf(&recv&failed!&); &&&&&&&&&&&&&&&&&&&&&&closesocket(sClient); &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&WSACleanup(); &&&&&&&&&&&&&&&&&&&&&return&-1; &&&&&&&&&&&&&&&&&} &&&&&&&&&&&&&} &&&&&&&&&} &&&&&&&&&&break; &&&&&} &}&
#include &winsock2.h&&&&&&&&&&&&& //winsock.h (2种套接字版本)
#pragma comment(lib,&ws2_32.lib&) //wsock32.lib
retVal=ioctlsocket(sServer,FIONBIO,(u_long *)&imode); //第3个参数通常设为1(同时第2个参数设为FIONBIO),表示非阻塞模式
a. //绑定套接字并将其设置为监听状态
&SOCKADDR_IN addrS
&addrServ.sin_family=AF_INET;
&addrServ.sin_port& =htons(5000);
&addrServ.sin_addr.S_un.S_addr=inet_addr(&192.168.0.102&);
&retVal=bind(sServer,(SOCKADDR *)&addrServ,sizeof(addrServ)); //绑定套接字到某一个具体的服务器
这一段代码表明,bind函数需要定义一个addrServ,并且要为每个字段赋值。
b. retVal=listen(sServer,1); //第二个参数,表示最大连接数目
<span style="color: #.
//接受连接
&sockaddr_in addrC //定义一个临时地址,用于接受连接(注意:某个客户端由Client.cpp确定)
&int len=sizeof(sockaddr_in);
&SOCKET sC
&while(true)
&&sClient=accept(sServer,(sockaddr *)&addrClient,&len);
&&if(sClient == INVALID_SOCKET)
&&&errcode=WSAGetLastError();
&&&if(errcode == WSAEWOULDBLOCK)& //表示没有客户端发起连接,继续循环
<span style="color: #.
retVal=recv(sClient,buf,strlen(buf),0);//第4个参数,表示影响该函数的行为(通常设为0)
retVal=send(sClient,buf,strlen(buf),0); //a.回显接收数据;b.第四个参数:0?
------------------------------------------------------------------------------------------------
<span style="color: #.
addrServ.sin_port& =htons(5000); //为什么要使用htons宏?前者的字段类型和宏的返回值类型一致
&addrServ.sin_addr.S_un.S_addr=inet_addr(&192.168.0.102&); //同理,后者函数的返回值类型和字段类型一致
<span style="color: #.
&&//scanf(buf);&//问题①:为何这两个发送字符串我发送不了?
&&strcpy(buf,&Hello TCP!&); //发送固定字符串
<span style="color: #.
问题②:下次继续做实验,bind failed的原因,而且是Client.cpp端出现的 真奇怪?(自己有调试,结果发现port字段和自己设置的不一致,不知为何)
了这篇文章
类别:┆阅读(0)┆评论(0)

我要回帖

更多关于 errcode 48001 的文章

 

随机推荐